// Command astra is the unified CLI: interactive REPL, MCP server, and auth.
//
// Install: go install github.com/ClareAI/astra-insight-mcp/cmd/astra@latest
package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/ClareAI/astra-insight-mcp/internal/app"
	"github.com/ClareAI/astra-insight-mcp/internal/version"
)

func main() {
	args := os.Args[1:]
	debug, rest := stripDebugFlags(args)

	if len(rest) == 0 {
		app.RunREPL(debug)
		return
	}

	switch rest[0] {
	case "help", "-h", "--help":
		printUsage(os.Stdout)
	case "version", "-v", "--version":
		fmt.Println(version.Version)
	case "server", "mcp":
		fs := flag.NewFlagSet("server", flag.ExitOnError)
		sdebug := fs.Bool("debug", false, "print full curl commands for every gateway API call")
		_ = fs.Parse(rest[1:])
		app.RunMCPServer(debug || *sdebug)
	case "auth", "configure", "setup", "config":
		app.RunAuth(rest[1:])
	case "chat":
		if len(rest) > 1 {
			fmt.Fprintf(os.Stderr, "astra chat: unexpected arguments: %q\n", rest[1:])
			os.Exit(2)
		}
		app.RunREPL(debug)
	default:
		fmt.Fprintf(os.Stderr, "unknown command %q\n\n", rest[0])
		printUsage(os.Stderr)
		os.Exit(2)
	}
}

func stripDebugFlags(args []string) (debug bool, rest []string) {
	for _, a := range args {
		if a == "-debug" || a == "--debug" {
			debug = true
			continue
		}
		rest = append(rest, a)
	}
	return debug, rest
}

func printUsage(w *os.File) {
	fmt.Fprintf(w, `astra — Astra Insight CLI (agent optimizer + MCP server)

Usage:
  astra [flags]              Interactive REPL (default)
  astra chat [flags]         Same as above
  astra server [flags]       Run Streamable HTTP MCP server (/mcp, /healthz)
  astra auth                 Configure LLM + Astra platform keys (interactive)
  astra auth clear           Remove all saved credentials
  astra auth status          Show current auth configuration
  astra auth --oauth         Browser OAuth PKCE login (advanced)
  astra version              Print version
  astra help                 Show this help

Global flags (before subcommand):
  -debug, --debug            Verbose gateway curl traces (REPL + can combine with server)

Examples:
  astra                      Start REPL (prompts for keys on first run)
  astra auth                 Set up or change LLM + Astra keys
  astra auth clear           Clear all keys and start fresh
  astra auth status          Check what's configured
  astra server               Run MCP server
  astra auth --oauth --env dev

Config file: ~/.astra/llm.json (LLM_* env vars override for a single session)

`)
}
