package cmd

import "fmt"

type ParsedArgs struct {
	Tailscale    bool
	Help         bool
	Login        bool
	AccountsList bool
	Logout       bool
	AccountName  string
	Proxies      []string
	ResetHwid    bool
	DeepClean    bool
	DryRun       bool
}

func ParseArgs(argv []string) (ParsedArgs, error) {
	var args ParsedArgs

	for i := 0; i < len(argv); i++ {
		arg := argv[i]

		switch arg {
		case "login", "add-account":
			args.Login = true
			if i+1 < len(argv) && len(argv[i+1]) > 0 && argv[i+1][0] != '-' {
				i++
				args.AccountName = argv[i]
			}

		case "logout", "remove-account":
			args.Logout = true
			if i+1 < len(argv) && len(argv[i+1]) > 0 && argv[i+1][0] != '-' {
				i++
				args.AccountName = argv[i]
			}

		case "accounts", "list-accounts":
			args.AccountsList = true

		case "reset-hwid", "reset":
			args.ResetHwid = true

		case "--deep-clean":
			args.DeepClean = true

		case "--dry-run":
			args.DryRun = true

		case "--tailscale":
			args.Tailscale = true

		case "--help", "-h":
			args.Help = true

		default:
			if len(arg) > len("--proxy=") && arg[:len("--proxy=")] == "--proxy=" {
				raw := arg[len("--proxy="):]
				parts := splitComma(raw)
				for _, p := range parts {
					if p != "" {
						args.Proxies = append(args.Proxies, p)
					}
				}
			} else {
				return args, fmt.Errorf("Unknown argument: %s", arg)
			}
		}
	}

	return args, nil
}

func splitComma(s string) []string {
	var result []string
	start := 0
	for i := 0; i <= len(s); i++ {
		if i == len(s) || s[i] == ',' {
			part := trim(s[start:i])
			if part != "" {
				result = append(result, part)
			}
			start = i + 1
		}
	}
	return result
}

func trim(s string) string {
	start := 0
	end := len(s)
	for start < end && (s[start] == ' ' || s[start] == '\t') {
		start++
	}
	for end > start && (s[end-1] == ' ' || s[end-1] == '\t') {
		end--
	}
	return s[start:end]
}

func PrintHelp(version string) {
	fmt.Printf("cursor-api-proxy v%s\n\n", version)
	fmt.Println("Usage:")
	fmt.Println("  cursor-api-proxy [options]")
	fmt.Println("")
	fmt.Println("Commands:")
	fmt.Println("  login [name]              Log into a Cursor account (saved to ~/.cursor-api-proxy/accounts/)")
	fmt.Println("  login [name] --proxy=...  Same, but with a proxy from a comma-separated list")
	fmt.Println("  logout <name>             Remove a saved Cursor account")
	fmt.Println("  accounts                  List saved accounts with plan info")
	fmt.Println("  reset-hwid                Reset Cursor machine/telemetry IDs (anti-ban)")
	fmt.Println("  reset-hwid --deep-clean   Also wipe session storage and cookies")
	fmt.Println("")
	fmt.Println("Options:")
	fmt.Println("  --tailscale     Bind to 0.0.0.0 for tailnet/LAN access")
	fmt.Println("  -h, --help      Show this help message")
}
