package agent

import (
	"encoding/json"
	"os"
	"path/filepath"
	"runtime"
)

func getCandidates(agentScriptPath, configDirOverride string) []string {
	if configDirOverride != "" {
		return []string{filepath.Join(configDirOverride, "cli-config.json")}
	}

	var result []string

	if dir := os.Getenv("CURSOR_CONFIG_DIR"); dir != "" {
		result = append(result, filepath.Join(dir, "cli-config.json"))
	}

	if agentScriptPath != "" {
		agentDir := filepath.Dir(agentScriptPath)
		result = append(result, filepath.Join(agentDir, "..", "data", "config", "cli-config.json"))
	}

	home := os.Getenv("HOME")
	if home == "" {
		home = os.Getenv("USERPROFILE")
	}

	switch runtime.GOOS {
	case "windows":
		local := os.Getenv("LOCALAPPDATA")
		if local == "" {
			local = filepath.Join(home, "AppData", "Local")
		}
		result = append(result, filepath.Join(local, "cursor-agent", "cli-config.json"))
	case "darwin":
		result = append(result, filepath.Join(home, "Library", "Application Support", "cursor-agent", "cli-config.json"))
	default:
		xdg := os.Getenv("XDG_CONFIG_HOME")
		if xdg == "" {
			xdg = filepath.Join(home, ".config")
		}
		result = append(result, filepath.Join(xdg, "cursor-agent", "cli-config.json"))
	}

	return result
}

func RunMaxModePreflight(agentScriptPath, configDirOverride string) {
	for _, candidate := range getCandidates(agentScriptPath, configDirOverride) {
		data, err := os.ReadFile(candidate)
		if err != nil {
			continue
		}

		// Strip BOM if present
		if len(data) >= 3 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF {
			data = data[3:]
		}

		var raw map[string]interface{}
		if err := json.Unmarshal(data, &raw); err != nil {
			continue
		}
		if raw == nil || len(raw) <= 1 {
			continue
		}

		raw["maxMode"] = true
		if model, ok := raw["model"].(map[string]interface{}); ok {
			model["maxMode"] = true
		}

		out, err := json.MarshalIndent(raw, "", "  ")
		if err != nil {
			continue
		}
		if err := os.WriteFile(candidate, out, 0644); err != nil {
			continue
		}
		return
	}
}
