package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"os/exec"

	"github.com/spf13/cobra"

	"github.com/Warky-Devs/vecna.git/pkg/config"
)

var editConfigCmd = &cobra.Command{
	Use:   "editconfig",
	Short: "Open the vecna config file in your editor",
	RunE:  runEditConfig,
}

func init() {
	rootCmd.AddCommand(editConfigCmd)
}

func runEditConfig(cmd *cobra.Command, _ []string) error {
	path := config.ResolveFile(cfgFile)

	if _, err := os.Stat(path); os.IsNotExist(err) {
		if err := createDefaultConfig(path); err != nil {
			return fmt.Errorf("create default config: %w", err)
		}
	}

	fmt.Println(path)

	editor := resolveEditor()
	c := exec.CommandContext(context.Background(), editor, path)
	c.Stdin = os.Stdin
	c.Stdout = os.Stdout
	c.Stderr = os.Stderr
	if err := c.Run(); err != nil {
		return fmt.Errorf("editor %q exited with error: %w", editor, err)
	}
	return nil
}

// resolveEditor returns $EDITOR, falling back to nvim then nano.
func resolveEditor() string {
	if e := os.Getenv("EDITOR"); e != "" {
		return e
	}
	for _, e := range []string{"nvim", "nano"} {
		if path, err := exec.LookPath(e); err == nil {
			return path
		}
	}
	return "nano"
}

// createDefaultConfig writes a minimal JSON config skeleton to path.
func createDefaultConfig(path string) error {
	skeleton := config.Config{
		Server: config.ServerConfig{
			Port:    8080,
			Host:    "0.0.0.0",
			APIKeys: []string{},
		},
		Metrics: config.MetricsConfig{
			Enabled: false,
			Path:    "/metrics",
		},
		Forward: config.ForwardConfig{
			Default: "default",
			Targets: map[string]config.ForwardTarget{
				"default": {
					APIType: "openai",
					Model:   "text-embedding-3-small",
					Endpoints: []config.EndpointConfig{
						{URL: "https://api.openai.com", Priority: 10},
					},
				},
			},
		},
		Adapter: config.AdapterConfig{
			Type:         "truncate",
			SourceDim:    1536,
			TargetDim:    768,
			TruncateMode: "from_end",
			PadMode:      "at_end",
		},
	}

	f, err := os.Create(path)
	if err != nil {
		return fmt.Errorf("create %s: %w", path, err)
	}
	defer func() { _ = f.Close() }()

	enc := json.NewEncoder(f)
	enc.SetIndent("", "  ")
	if err := enc.Encode(skeleton); err != nil {
		return fmt.Errorf("write default config: %w", err)
	}
	return nil
}
