package cli

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

	"github.com/spf13/cobra"
)

var configCmd = &cobra.Command{
	Use:    "config",
	Short:  "Manage pentestswarm configuration",
	Hidden: true, // 4.8.2: 'init' covers the common path; config.show is power-user
}

var configInitCmd = &cobra.Command{
	Use:     "init",
	Short:   "Interactive setup wizard — creates config.yaml",
	Example: "  pentestswarm config init",
	RunE: func(cmd *cobra.Command, args []string) error {
		reader := bufio.NewReader(os.Stdin)

		fmt.Println(colorCyan("\n  Pentest Swarm AI — Configuration Wizard\n"))
		fmt.Println(colorDim("  This will create a config.yaml file in the current directory.\n"))

		// Provider
		fmt.Printf("  %s\n", colorBold("LLM Provider"))
		fmt.Println("  1) Claude (Anthropic API — best quality, recommended)")
		fmt.Println("  2) Ollama (local models — full privacy, needs GPU)")
		fmt.Println("  3) LM Studio (local, OpenAI-compatible)")
		fmt.Println()
		provider := prompt(reader, "  Choose provider [1/2/3]", "1")

		var providerName, apiKey, endpoint, model string

		switch provider {
		case "1", "claude":
			providerName = "claude"
			model = "claude-sonnet-4-6"
			apiKey = prompt(reader, "  Claude API key (sk-ant-...)", "")
			if apiKey == "" {
				fmt.Println(colorYellow("  No API key provided. Set PENTESTSWARM_ORCHESTRATOR_API_KEY env var later."))
			}
		case "2", "ollama":
			providerName = "ollama"
			endpoint = prompt(reader, "  Ollama endpoint", "http://localhost:11434")
			model = prompt(reader, "  Model name", "llama3.1:8b")
		case "3", "lmstudio":
			providerName = "lmstudio"
			endpoint = prompt(reader, "  LM Studio endpoint", "http://localhost:1234")
			model = prompt(reader, "  Model name", "")
		default:
			providerName = "claude"
			model = "claude-sonnet-4-6"
		}

		fmt.Println()

		// Output format
		format := prompt(reader, "  Default report format [md/html/json/all]", "md")

		// Write config
		cfg := fmt.Sprintf(`# pentestswarm configuration
# Generated by: pentestswarm config init

server:
  host: "0.0.0.0"
  port: 8080

orchestrator:
  provider: "%s"
  model: "%s"
  api_key: "%s"
  endpoint: "%s"
  context_window: 200000
  max_tokens: 8192
  temperature: 0.1

# All agents inherit from orchestrator by default.
# Override per-agent only if using local fine-tuned models.
agents:
  recon: {}
  classifier: {}
  exploit: {}
  report: {}

tools:
  default_timeout: 300

scope:
  enforce_strict: true

logging:
  level: "info"
  format: "console"

# Default report format
# report_format: "%s"
`, providerName, model, apiKey, endpoint, format)

		configPath := "config.yaml"
		if err := os.WriteFile(configPath, []byte(cfg), 0644); err != nil {
			return fmt.Errorf("writing config: %w", err)
		}

		fmt.Println(colorGreen(fmt.Sprintf("  Config written to %s", configPath)))
		fmt.Println()
		fmt.Println("  Next steps:")
		fmt.Printf("    %s  Run a health check\n", colorDim("pentestswarm doctor"))
		fmt.Printf("    %s  Launch your first scan\n", colorDim("pentestswarm scan target.com --scope target.com"))
		fmt.Println()

		return nil
	},
}

var configShowCmd = &cobra.Command{
	Use:     "show",
	Short:   "Print current configuration (secrets redacted)",
	Example: "  pentestswarm config show",
	RunE: func(cmd *cobra.Command, args []string) error {
		data, err := os.ReadFile("config.yaml")
		if err != nil {
			return fmt.Errorf("no config.yaml found — run 'pentestswarm config init'")
		}

		// Redact secrets
		lines := strings.Split(string(data), "\n")
		for i, line := range lines {
			if strings.Contains(line, "api_key:") || strings.Contains(line, "password:") ||
				strings.Contains(line, "token:") || strings.Contains(line, "secret:") {
				parts := strings.SplitN(line, ":", 2)
				if len(parts) == 2 && strings.TrimSpace(parts[1]) != `""` && strings.TrimSpace(parts[1]) != "" {
					lines[i] = parts[0] + ": \"****REDACTED****\""
				}
			}
		}

		fmt.Println(strings.Join(lines, "\n"))
		return nil
	},
}

var configValidateCmd = &cobra.Command{
	Use:     "validate",
	Short:   "Validate the configuration file",
	Example: "  pentestswarm config validate",
	RunE: func(cmd *cobra.Command, args []string) error {
		_, err := os.ReadFile("config.yaml")
		if err != nil {
			return fmt.Errorf("no config.yaml found — run 'pentestswarm config init'")
		}
		// TODO: load and validate with config.Validate
		fmt.Println(colorGreen("  Config is valid."))
		return nil
	},
}

func prompt(reader *bufio.Reader, question, defaultVal string) string {
	if defaultVal != "" {
		fmt.Printf("  %s [%s]: ", question, colorDim(defaultVal))
	} else {
		fmt.Printf("  %s: ", question)
	}

	input, _ := reader.ReadString('\n')
	input = strings.TrimSpace(input)

	if input == "" {
		return defaultVal
	}
	return input
}

func init() {
	configCmd.AddCommand(configInitCmd)
	configCmd.AddCommand(configShowCmd)
	configCmd.AddCommand(configValidateCmd)

	rootCmd.AddCommand(configCmd)
}
