package main

import (
	"encoding/json"
	"fmt"
	"io"
	"os"

	"github.com/lrstanley/go-ytdlp"
	"github.com/spf13/cobra"
)

func main() {
	cli := &cobra.Command{
		Use:           "go-ytdlp",
		Short:         "A simple CLI wrapper for go-ytdlp.",
		SilenceUsage:  true,
		SilenceErrors: true,
	}

	cli.AddCommand(&cobra.Command{
		Use:   "flags-to-json [flags...]",
		Short: "Converts yt-dlp flags to a JSON config.",
		Long:  "Converts yt-dlp flags to a JSON config. Note that this does not validate the flags.",
		Args:  cobra.MinimumNArgs(1),
		RunE: func(cmd *cobra.Command, args []string) (err error) {
			// The go-ytdlp library documentation mentions FlagsToJSON and SetFlagConfig,
			// but these methods are missing from the generated code in the current version.
			// Therefore, we cannot implement this command yet.
			return fmt.Errorf("flags-to-json is not supported by the underlying go-ytdlp library")
		},
	})

	cli.AddCommand(&cobra.Command{
		Use:   "json-to-flags",
		Short: "Converts a JSON config to yt-dlp flags.",
		Long:  "Converts a JSON config to yt-dlp flags. Note that this does not validate the flags. Reads from stdin.",
		Args:  cobra.NoArgs,
		RunE: func(cmd *cobra.Command, args []string) (err error) {
			var in []byte
			in, err = io.ReadAll(cmd.InOrStdin())
			if err != nil {
				return err
			}

			// Manually unmarshal into FlagConfig since JSONToFlags helper is missing
			var cfg ytdlp.FlagConfig
			if err := json.Unmarshal(in, &cfg); err != nil {
				return fmt.Errorf("failed to unmarshal JSON: %w", err)
			}

			flags := cfg.ToFlags()
			for _, flag := range flags {
				fmt.Fprintln(cmd.OutOrStdout(), flag)
			}
			return nil
		},
	})

	if err := cli.Execute(); err != nil {
		fmt.Fprintln(os.Stderr, "Error:", err)
		os.Exit(1)
	}
}
