package main

import (
	"fmt"
	"strconv"

	"github.com/orchard9/rdev/internal/sdlc"
	"github.com/spf13/cobra"
)

var configCmd = &cobra.Command{
	Use:   "config",
	Short: "Manage SDLC configuration",
}

var configShowCmd = &cobra.Command{
	Use:   "show",
	Short: "Show current configuration",
	RunE: func(_ *cobra.Command, _ []string) error {
		root := mustResolveRoot()

		cfg, err := sdlc.LoadConfig(root)
		if err != nil {
			return err
		}

		if jsonOutput {
			return printJSON(cfg)
		}

		fmt.Printf("SDLC Config (v%d)\n", cfg.Version)
		fmt.Printf("  Project: %s\n", cfg.Project.Name)
		if cfg.Project.Type != "" {
			fmt.Printf("  Type:    %s\n", cfg.Project.Type)
		}
		fmt.Printf("  Main:    %s\n", cfg.Branches.Main)
		fmt.Printf("  Prefix:  %s\n", cfg.Branches.FeaturePrefix)
		fmt.Println()

		fmt.Println("Enabled Phases:")
		for _, p := range cfg.Phases.Enabled {
			fmt.Printf("  - %s\n", p)
		}
		fmt.Println()

		fmt.Println("Compliance:")
		fmt.Printf("  Require Approvals: %v\n", cfg.Compliance.RequireApprovals)
		fmt.Printf("  Require Branch:    %v\n", cfg.Compliance.RequireBranch)
		fmt.Printf("  Require QA:        %v\n", cfg.Compliance.RequireQA)

		return nil
	},
}

var configSetCmd = &cobra.Command{
	Use:   "set <key> <value>",
	Short: "Set a configuration value",
	Args:  cobra.ExactArgs(2),
	RunE: func(_ *cobra.Command, args []string) error {
		root := mustResolveRoot()

		cfg, err := sdlc.LoadConfig(root)
		if err != nil {
			return err
		}

		key, value := args[0], args[1]
		switch key {
		case "project.name":
			cfg.Project.Name = value
		case "project.type":
			cfg.Project.Type = value
		case "branches.main":
			cfg.Branches.Main = value
		case "branches.feature_prefix":
			cfg.Branches.FeaturePrefix = value
		case "compliance.require_approvals":
			b, err := strconv.ParseBool(value)
			if err != nil {
				return fmt.Errorf("invalid boolean value for %s: %w", key, err)
			}
			cfg.Compliance.RequireApprovals = b
		case "compliance.require_branch":
			b, err := strconv.ParseBool(value)
			if err != nil {
				return fmt.Errorf("invalid boolean value for %s: %w", key, err)
			}
			cfg.Compliance.RequireBranch = b
		case "compliance.require_qa":
			b, err := strconv.ParseBool(value)
			if err != nil {
				return fmt.Errorf("invalid boolean value for %s: %w", key, err)
			}
			cfg.Compliance.RequireQA = b
		default:
			return fmt.Errorf("unknown config key: %s", key)
		}

		if err := cfg.Save(root); err != nil {
			return err
		}

		if jsonOutput {
			return printJSON(map[string]string{"key": key, "value": value, "status": "set"})
		}

		fmt.Printf("Set %s = %s\n", key, value)
		return nil
	},
}

func init() {
	configCmd.AddCommand(configShowCmd, configSetCmd)
	rootCmd.AddCommand(configCmd)
}
