package main

import (
	"context"
	"flag"
	"log"
	"strconv"
	"strings"
	"time"

	"git.pengzhan.dev/aimaren/internal/config"
	"git.pengzhan.dev/aimaren/internal/crawler"
	"git.pengzhan.dev/aimaren/internal/driver"
	"git.pengzhan.dev/aimaren/internal/notifier"
	"git.pengzhan.dev/aimaren/internal/storage"
)

func main() {
	chatIDsFlag := flag.String("chatids", "", "Comma-separated list of Telegram chat IDs to override config")
	debugMode := flag.Bool("debug", false, "Enable debug mode to print raw HTML from scrapes.")
	flag.Parse()

	cfg, err := config.Load()
	if err != nil {
		log.Fatalf("❌ Failed to load configuration: %v", err)
	}

	if *chatIDsFlag != "" {
		log.Printf("📲 Overriding chat IDs with flag: %s", *chatIDsFlag)
		var parsedIDs []int64
		idStrings := strings.Split(*chatIDsFlag, ",")
		for _, idStr := range idStrings {
			id, err := strconv.ParseInt(strings.TrimSpace(idStr), 10, 64)
			if err != nil {
				log.Fatalf("❌ Invalid chat ID in --chatids flag: '%s'", idStr)
			}
			parsedIDs = append(parsedIDs, id)
		}
		cfg.Telegram.ChatIDs = parsedIDs
	}

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	if *debugMode {
		ctx = context.WithValue(ctx, crawler.DebugContextKey, true)
		log.Println("🐞 Debug mode enabled.")
	}

	store, err := storage.NewFirestoreClient(ctx, cfg.GCPProjectID)
	if err != nil {
		log.Fatalf("❌ Failed to create Firestore client: %v", err)
	}
	defer store.Close()

	notify, err := notifier.NewTelegramNotifier(cfg)
	if err != nil {
		log.Fatalf("❌ Failed to create Telegram notifier: %v", err)
	}

	appDriver := driver.New(store, notify)

	if err := appDriver.Run(ctx); err != nil {
		log.Fatalf("❌ Crawler run failed: %v", err)
	}

	log.Println("✅ Crawler run completed successfully.")
}
