// Package cli implements the wallfacer CLI subcommands.
package cli

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"

	"changkun.de/x/wallfacer/internal/logger"
)

// Version is set at build time via -ldflags (e.g. -X cli.Version=1.2.3).
// When empty (dev build), the doctor subcommand displays "dev" as the
// version string.
var Version = ""

// ConfigDir returns the default wallfacer configuration directory.
func ConfigDir() string {
	home, err := os.UserHomeDir()
	if err != nil {
		logger.Fatal("home dir", "error", err)
	}
	return filepath.Join(home, ".wallfacer")
}

// PrintUsage writes the CLI help text to stderr.
func PrintUsage() {
	v := Version
	if v == "" {
		v = "dev"
	}
	fmt.Fprintf(os.Stderr, "wallfacer %s\n\n", v)
	fmt.Fprintf(os.Stderr, "Usage: wallfacer <command> [arguments]\n\n")
	fmt.Fprintf(os.Stderr, "Commands:\n")
	fmt.Fprintf(os.Stderr, "  run          start the task board server\n")
	fmt.Fprintf(os.Stderr, "  desktop      launch the native desktop app (requires -tags desktop build)\n")
	fmt.Fprintf(os.Stderr, "  status       print running board state to terminal\n")
	fmt.Fprintf(os.Stderr, "  spec         spec document tools (validate, ...)\n")
	fmt.Fprintf(os.Stderr, "  doctor       check prerequisites and configuration\n")
	fmt.Fprintf(os.Stderr, "\nRun 'wallfacer <command> -help' for more information on a command.\n")
}

// initConfigDir ensures the configuration directory exists and seeds the .env
// template file if it does not already exist.
func initConfigDir(configDir, envFile string) {
	if err := os.MkdirAll(configDir, 0755); err != nil {
		logger.Fatal("create config dir", "error", err)
	}

	if _, err := os.Stat(envFile); os.IsNotExist(err) {
		content := "# =============================================================================\n" +
			"# Claude Code sandbox (default)\n" +
			"# =============================================================================\n\n" +
			"# Authentication: set ONE of the two variables below.\n" +
			"CLAUDE_CODE_OAUTH_TOKEN=your-oauth-token-here\n" +
			"# ANTHROPIC_API_KEY=sk-ant-...\n\n" +
			"# Optional: custom Anthropic-compatible API base URL.\n" +
			"# ANTHROPIC_BASE_URL=https://api.anthropic.com\n\n" +
			"# Optional: default model for Claude tasks.\n" +
			"# CLAUDE_DEFAULT_MODEL=\n\n" +
			"# Optional: model for auto-generating task titles (falls back to default model).\n" +
			"# CLAUDE_TITLE_MODEL=\n\n" +
			"# =============================================================================\n" +
			"# OpenAI Codex (set OPENAI_API_KEY to enable Codex-typed tasks).\n" +
			"# =============================================================================\n\n" +
			"# Authentication: set your OpenAI API key.\n" +
			"# OPENAI_API_KEY=sk-...\n\n" +
			"# Optional: custom OpenAI-compatible API base URL.\n" +
			"# OPENAI_BASE_URL=https://api.openai.com/v1\n\n" +
			"# Optional: default model for Codex tasks.\n" +
			"# CODEX_DEFAULT_MODEL=codex-mini-latest\n\n" +
			"# Optional: model for auto-generating task titles with Codex (falls back to CODEX_DEFAULT_MODEL).\n" +
			"# CODEX_TITLE_MODEL=codex-mini-latest\n\n" +
			"# Optional: enable fast-mode sandbox hints by default (set to false to disable).\n" +
			"WALLFACER_SANDBOX_FAST=true\n"
		if err := os.WriteFile(envFile, []byte(content), 0600); err != nil {
			logger.Fatal("create env file", "error", err)
		}
		logger.Main.Info("created env file — edit it and set your token", "path", envFile)
	}
}

// envOrDefault returns the value of the environment variable key, or fallback
// if the variable is unset or empty.
func envOrDefault(key, fallback string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return fallback
}

// isWSL reports whether the process is running inside Windows Subsystem for Linux.
func isWSL() bool {
	return os.Getenv("WSL_DISTRO_NAME") != "" || os.Getenv("WSL_INTEROP") != ""
}

// openBrowser launches the platform's default browser with the given URL.
// Under WSL, it delegates to cmd.exe so the Windows host browser opens.
func openBrowser(url string) {
	switch runtime.GOOS {
	case "darwin":
		_ = exec.Command("open", url).Start()
	case "windows":
		_ = exec.Command("cmd", "/c", "start", url).Start()
	case "linux":
		if isWSL() {
			_ = exec.Command("cmd.exe", "/c", "start", url).Start()
		} else {
			_ = exec.Command("xdg-open", url).Start()
		}
	}
}
