// Package main is the entrypoint for the claude-failover daemon.
package main

import (
	"context"
	"flag"
	"log"
	"os"
	"os/signal"
	"syscall"

	"forge.secuaas.ovh/olivier/claude-failover/internal/api"
	"forge.secuaas.ovh/olivier/claude-failover/internal/config"
	"forge.secuaas.ovh/olivier/claude-failover/internal/lifecycle"
	"forge.secuaas.ovh/olivier/claude-failover/internal/state"
	"forge.secuaas.ovh/olivier/claude-failover/internal/tmux"
)

const version = "0.1.0"

func main() {
	var cfgPath string
	flag.StringVar(&cfgPath, "config", "config.yaml", "path to YAML config file")
	flag.Parse()

	log.SetFlags(log.LstdFlags | log.Lmicroseconds | log.LUTC)
	log.Printf("claude-failover v%s starting (config=%s)", version, cfgPath)

	cfg, err := config.Load(cfgPath)
	if err != nil {
		log.Fatalf("config load failed: %v", err)
	}
	log.Printf("config loaded: %d account(s), pool min=%d max=%d",
		len(cfg.Accounts), cfg.Pool.Autonomous.Min, cfg.Pool.Autonomous.Max)

	// Initialise state — reload from disk if a snapshot exists.
	stateFile := cfg.Checkpoint.Dir + "/state.json"
	s, err := state.LoadFromFile(stateFile)
	if err != nil {
		log.Fatalf("state init failed: %v", err)
	}
	log.Printf("state loaded (%d sessions tracked)", len(s.Sessions))

	// Initialise tmux client and lifecycle manager.
	tmuxClient := tmux.NewExecClient()
	lm := lifecycle.New(tmuxClient, s, cfg)
	lm.EnsureAllSessions()

	// Block until SIGINT or SIGTERM.
	ctx, cancel := signal.NotifyContext(context.Background(),
		syscall.SIGINT, syscall.SIGTERM)
	defer cancel()

	go lm.Run(ctx)

	// Start HTTP API server.
	listenAddr := cfg.MCPHTTP.Listen
	if listenAddr == "" {
		listenAddr = "127.0.0.1:9090"
	}
	srv := api.New(listenAddr, s)
	go func() {
		if err := srv.Start(); err != nil {
			log.Printf("API server error: %v", err)
			os.Exit(1)
		}
	}()
	log.Printf("claude-failover v%s started, API on %s", version, listenAddr)

	<-ctx.Done()
	log.Printf("shutdown signal received — flushing state and exiting")
	if err := s.Flush(); err != nil {
		log.Printf("state flush warning: %v", err)
	}
}
