package main

import (
	"bufio"
	"context"
	"fmt"
	"os"
	"strings"
)

func main() {
	root, err := os.Getwd()
	if err != nil {
		fmt.Fprintln(os.Stderr, "error getting working directory:", err)
		os.Exit(1)
	}

	if err := loadConfig(root); err != nil {
		fmt.Fprintln(os.Stderr, "config error:", err)
		os.Exit(1)
	}

	apiKey := os.Getenv("OPENAI_API_KEY")
	baseURL := getEnvDefault("OPENAI_BASE_URL", "https://api.openai.com/v1")
	model := getEnvDefault("OPENAI_MODEL", "gpt-4o-mini")

	if apiKey == "" {
		fmt.Fprintln(os.Stderr, "OPENAI_API_KEY is not set")
		os.Exit(1)
	}

	client := NewClient(baseURL, apiKey, model)
	orch := NewOrchestrator(client, root)

	fmt.Printf("NyxTex agent (manager + programmer + qa) — model=%s  root=%s\n", model, root)
	fmt.Println("Type your request. Ctrl+D or /exit to quit.")

	reader := bufio.NewReader(os.Stdin)
	for {
		fmt.Print("\n> ")
		input, err := readUserInput(reader)
		if err != nil {
			fmt.Println()
			return
		}
		input = strings.TrimSpace(input)
		if input == "" {
			continue
		}
		if input == "/exit" || input == "/quit" {
			return
		}

		reply, err := orch.Handle(context.Background(), input)
		if err != nil {
			fmt.Fprintln(os.Stderr, "error:", err)
			continue
		}
		if strings.TrimSpace(reply) != "" {
			fmt.Println()
			fmt.Println(reply)
		}
	}
}

func readUserInput(r *bufio.Reader) (string, error) {
	line, err := r.ReadString('\n')
	if err != nil && line == "" {
		return "", err
	}
	return line, nil
}

func getEnvDefault(key, def string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return def
}
