package main

import (
	"bufio"
	"context"
	"fmt"
	"os"
	"strings"

	"github.com/spf13/cobra"

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

var searchCmd = &cobra.Command{
	Use:   "search",
	Short: "Scan the network for LLM servers and add one to the config",
	RunE:  runSearch,
}

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

func runSearch(_ *cobra.Command, _ []string) error {
	in := bufio.NewReader(os.Stdin)

	fmt.Println("Scanning for LLM servers (Ollama, LM Studio, vLLM, LocalAI, Jan, Kobold, Tabby)...")
	servers := discovery.Scan(context.Background())

	if len(servers) == 0 {
		fmt.Println("No servers found.")
		return nil
	}

	fmt.Printf("\nFound %d server(s):\n\n", len(servers))
	for i, s := range servers {
		modelList := strings.Join(s.Models, ", ")
		if modelList == "" {
			modelList = "(no models listed)"
		}
		fmt.Printf("  [%d] %s  %s\n      Models: %s\n\n", i+1, s.Kind.Name, s.BaseURL, modelList)
	}

	// Select server
	chosen, err := promptInt(in, fmt.Sprintf("Select server [1-%d]: ", len(servers)), 1, len(servers))
	if err != nil {
		return err
	}
	srv := servers[chosen-1]

	// Select model
	var model string
	switch {
	case len(srv.Models) == 1:
		model = srv.Models[0]
		fmt.Printf("Using model: %s\n", model)
	case len(srv.Models) > 1:
		fmt.Println("\nAvailable models:")
		for i, m := range srv.Models {
			fmt.Printf("  [%d] %s\n", i+1, m)
		}
		idx, err := promptInt(in, fmt.Sprintf("Select model [1-%d]: ", len(srv.Models)), 1, len(srv.Models))
		if err != nil {
			return err
		}
		model = srv.Models[idx-1]
	default:
		model, err = promptString(in, "Model name: ", "")
		if err != nil {
			return err
		}
	}

	// Target name in config
	defaultName := strings.ToLower(strings.ReplaceAll(srv.Kind.Name, " ", "_"))
	targetName, err := promptString(in, fmt.Sprintf("Target name in config [%s]: ", defaultName), defaultName)
	if err != nil {
		return err
	}

	// API key
	keyPrompt := "API key (leave empty if none): "
	if srv.Kind.NeedsKey {
		keyPrompt = "API key: "
	}
	apiKey, err := promptString(in, keyPrompt, "")
	if err != nil {
		return err
	}

	target := config.ForwardTarget{
		APIType: srv.Kind.APIType,
		Model:   model,
		APIKey:  apiKey,
		Endpoints: []config.EndpointConfig{
			{URL: srv.BaseURL, Priority: 10},
		},
		TimeoutSecs:      30,
		CooldownSecs:     60,
		PriorityDecay:    2,
		PriorityRecovery: 5,
	}

	cfgPath := config.ResolveFile(cfgFile)

	// Create default config if it doesn't exist yet
	if _, err := os.Stat(cfgPath); os.IsNotExist(err) {
		if err := createDefaultConfig(cfgPath); err != nil {
			return fmt.Errorf("create default config: %w", err)
		}
	}

	if err := config.SaveTarget(cfgPath, targetName, target); err != nil {
		return err
	}

	fmt.Printf("\nAdded target %q to %s\n", targetName, cfgPath)
	return nil
}
