package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/spf13/cobra"

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

var modelsCmd = &cobra.Command{
	Use:   "models",
	Short: "List models available on each configured forwarder",
	RunE:  runModels,
}

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

func runModels(_ *cobra.Command, _ []string) error {
	cfg, err := config.Load(cfgFile)
	if err != nil {
		return fmt.Errorf("load config: %w", err)
	}

	if len(cfg.Forward.Targets) == 0 {
		fmt.Println("No forwarder targets configured.")
		return nil
	}

	ctx := context.Background()

	for targetName, target := range cfg.Forward.Targets {
		fmt.Printf("[ %s ]\n", targetName)

		for _, ep := range target.Endpoints {
			kind := discovery.Kind{
				Name:    targetName,
				APIType: target.APIType,
				Port:    0, // not used by Models()
			}

			models, err := discovery.Models(ctx, ep.URL, kind)
			if err != nil {
				fmt.Printf("  %s  error: %s\n\n", ep.URL, err)
				continue
			}

			if len(models) == 0 {
				fmt.Printf("  %s  (no models listed)\n\n", ep.URL)
				continue
			}

			fmt.Printf("  %s\n", ep.URL)
			for _, m := range models {
				marker := "  "
				if m == target.Model {
					marker = "* "
				}
				fmt.Printf("    %s%s\n", marker, m)
			}

			if target.Model != "" && !contains(models, target.Model) {
				fmt.Printf("    ! configured model %q not found in list\n", target.Model)
			}
			fmt.Println()
		}

		if len(target.Endpoints) == 0 {
			fmt.Printf("  (no endpoints configured)\n\n")
		}

		fmt.Printf("  API type : %s\n", target.APIType)
		fmt.Printf("  Model    : %s\n\n", strings.TrimSpace(target.Model))
	}

	return nil
}

func contains(ss []string, s string) bool {
	for _, v := range ss {
		if v == s {
			return true
		}
	}
	return false
}
