package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/fujin/anthropic-proxy/internal/auth"
	"github.com/fujin/anthropic-proxy/internal/config"
	"github.com/fujin/anthropic-proxy/internal/logging"
	"github.com/fujin/anthropic-proxy/internal/proxy"
	"github.com/fujin/anthropic-proxy/internal/server"
	"github.com/rs/zerolog/log"
)

func run() error {
	cfg, err := config.Load("config.yaml")
	if err != nil {
		return fmt.Errorf("load config: %w", err)
	}

	logging.Setup(logging.Config{
		Level:      cfg.Logging.Level,
		File:       cfg.Logging.File,
		MaxSizeMB:  cfg.Logging.MaxSizeMB,
		MaxBackups: cfg.Logging.MaxBackups,
		MaxAgeDays: cfg.Logging.MaxAgeDays,
		Compress:   cfg.Logging.Compress,
	})

	// Load credentials from ~/.claude/.credentials.json
	creds, err := config.LoadDefaultCredentials()
	if err != nil {
		return fmt.Errorf("load credentials: %w", err)
	}

	var cred *auth.Credential
	if len(creds) > 0 {
		cred = creds[0]
		// If token is expired, try refresh first
		if !cred.ExpiresAt.IsZero() && time.Now().After(cred.ExpiresAt) {
			log.Info().Msg("token expired, attempting refresh")
			refreshCtx, refreshCancel := context.WithTimeout(context.Background(), 15*time.Second)
			refreshErr := auth.RefreshToken(refreshCtx, cred)
			refreshCancel()
			if refreshErr != nil {
				log.Warn().Err(refreshErr).Msg("refresh failed, initiating login")
				cred = nil // fall through to login
			} else {
				log.Info().Msg("token refreshed")
			}
		}
	}

	if cred == nil {
		// Non-TTY check: if stdin is not a terminal, can't do interactive login
		fi, statErr := os.Stdin.Stat()
		if statErr == nil && (fi.Mode()&os.ModeCharDevice) == 0 {
			return fmt.Errorf("no valid credentials found; run the proxy interactively for initial login")
		}
		log.Info().Msg("no credentials found, starting OAuth login")
		cred, err = auth.Login(context.Background())
		if err != nil {
			return fmt.Errorf("login failed: %w", err)
		}
	}

	log.Info().Str("credential", cred.Email).Msg("credential loaded")

	pool := auth.NewPool([]*auth.Credential{cred})

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	pool.RefreshExpiring(context.Background())
	auth.StartBackgroundRefresh(ctx, pool)

	var profile *proxy.SniffedProfile
	if cfg.ClaudeBinary != "" {
		log.Info().Str("binary", cfg.ClaudeBinary).Msg("sniffing claude-code")
		profile, err = proxy.SniffClaudeCode(cfg.ClaudeBinary)
		if err != nil {
			log.Warn().Err(err).Msg("sniff failed, using defaults")
		}
	}

	log.Info().Int("port", cfg.Port).Msg("starting server")
	srv := server.New(cfg, pool, profile)

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		<-quit
		log.Info().Msg("shutting down")
		cancel()

		shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer shutdownCancel()

		if err := srv.Shutdown(shutdownCtx); err != nil {
			log.Error().Err(err).Msg("shutdown error")
		}
	}()

	if err := srv.Start(); err != nil && err != http.ErrServerClosed {
		return err
	}

	return nil
}

func main() {
	if err := run(); err != nil {
		log.Error().Err(err).Msg("fatal error")
		os.Exit(1)
	}
}
