// Command tg-apicreator-bot is the entry point. It wires the config, the
// SQLite store, the proxy manager, the rate limiter, the logger, the Telegram
// bot and the web admin panel together, then runs them until interrupted.
package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"os/signal"
	"strconv"
	"syscall"
	"time"

	"github.com/z/tg-apicreator-bot/internal/bot"
	"github.com/z/tg-apicreator-bot/internal/config"
	"github.com/z/tg-apicreator-bot/internal/database"
	"github.com/z/tg-apicreator-bot/internal/logging"
	"github.com/z/tg-apicreator-bot/internal/proxy"
	"github.com/z/tg-apicreator-bot/internal/ratelimit"
	"github.com/z/tg-apicreator-bot/internal/repository"
	"github.com/z/tg-apicreator-bot/internal/web"
)

func main() {
	configPath := flag.String("config", "config.yaml", "path to the YAML config file")
	flag.Parse()

	cfg, err := config.Load(*configPath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "config: %v\n", err)
		os.Exit(2)
	}

	db, err := database.Open(cfg.Database.Path)
	if err != nil {
		fmt.Fprintf(os.Stderr, "database: %v\n", err)
		os.Exit(1)
	}
	defer db.Close()

	repo := repository.New(db)

	// Overlay runtime-overridable settings (saved by the web panel) onto the
	// in-memory config so the bot starts with the last values an admin chose.
	overlaySettings(repo, cfg)

	lg, err := logging.New(repo, cfg.Logging.File, cfg.Logging.Level)
	if err != nil {
		fmt.Fprintf(os.Stderr, "logger: %v\n", err)
		os.Exit(1)
	}
	defer lg.Close()

	lg.Infof("main", "starting: db=%s web=%s bot admins=%v", cfg.Database.Path, cfg.Web.Addr, cfg.Bot.Admins)

	pm := proxy.New(repo)
	if err := pm.Reload(); err != nil {
		lg.Warnf("main", "proxy reload: %v (continuing with direct connection)", err)
	}

	lim := ratelimit.New(cfg.Limits.CooldownSeconds)

	b, err := bot.New(cfg, repo, pm, lim, lg)
	if err != nil {
		// Keep the admin panel usable so the operator can read logs and fix the
		// token without a restart; the bot stays offline until then.
		lg.Errorf("main", "bot init failed (starting web panel in degraded mode): %v", err)
		b = nil
	}

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	// Web panel runs in its own goroutine; the bot blocks the main goroutine.
	go func() {
		botName := ""
		if b != nil {
			botName = b.Me()
		}
		srv := web.New(cfg, repo, pm, lim, lg, botName)
		lg.Infof("main", "web panel listening on %s (base=%s)", cfg.Web.Addr, cfg.Web.BaseURL)
		if err := srv.Run(cfg.Web.Addr); err != nil {
			lg.Errorf("main", "web server stopped: %v", err)
			stop()
		}
	}()

	if b != nil {
		if err := b.Start(ctx); err != nil {
			lg.Infof("main", "bot stopped: %v", err)
		}
	} else {
		// Degraded mode: no bot, just keep the panel alive until interrupted.
		<-ctx.Done()
		lg.Infof("main", "shutting down (degraded): %v", ctx.Err())
	}
}

// overlaySettings applies persisted runtime knobs (daily limit, cooldown,
// whitelist, proxy mode/timeout) on top of the loaded config. Missing keys
// fall back to the config defaults.
func overlaySettings(repo *repository.Repository, cfg *config.Config) {
	if v, _ := repo.GetSetting("daily_limit"); v != "" {
		if n, err := strconv.Atoi(v); err == nil && n >= 0 {
			cfg.Limits.Daily = n
		}
	}
	if v, _ := repo.GetSetting("cooldown_seconds"); v != "" {
		if n, err := strconv.Atoi(v); err == nil && n >= 0 {
			cfg.Limits.CooldownSeconds = n
		}
	}
	if v, _ := repo.GetSetting("whitelist_enabled"); v != "" {
		cfg.Bot.WhitelistEnabled = v == "1" || v == "true"
	}
	if v, _ := repo.GetSetting("proxy_mode"); v == "none" || v == "round_robin" {
		cfg.Proxy.Mode = v
	}
	if v, _ := repo.GetSetting("proxy_timeout"); v != "" {
		if n, err := strconv.Atoi(v); err == nil && n > 0 {
			cfg.Proxy.TimeoutSeconds = n
		}
	}
}

// keep time imported even if unused in future edits
var _ = time.Second
