package main

import (
	"bssapp-backend/routes"
	"database/sql"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

func startTranslationSyncScheduler(pgDB *sql.DB, mssqlDB *sql.DB) {
	enabled := strings.TrimSpace(strings.ToLower(os.Getenv("TRANSLATION_SYNC_ENABLED")))
	if enabled == "0" || enabled == "false" || enabled == "off" {
		log.Println("🛑 Translation sync scheduler disabled")
		return
	}

	hour := 4
	if raw := strings.TrimSpace(os.Getenv("TRANSLATION_SYNC_HOUR")); raw != "" {
		if parsed, err := strconv.Atoi(raw); err == nil && parsed >= 0 && parsed <= 23 {
			hour = parsed
		}
	}

	limit := 30000
	if raw := strings.TrimSpace(os.Getenv("TRANSLATION_SYNC_LIMIT")); raw != "" {
		if parsed, err := strconv.Atoi(raw); err == nil && parsed > 0 {
			limit = parsed
		}
	}

	go func() {
		for {
			next := nextRunAt(time.Now(), hour)
			wait := time.Until(next)
			log.Printf("🕓 Translation sync next run at %s (in %s)", next.Format(time.RFC3339), wait.Round(time.Second))
			time.Sleep(wait)

			result, err := routes.PerformTranslationSync(pgDB, mssqlDB, routes.TranslationSyncOptions{
				AutoTranslate: true,
				Languages:     []string{"en", "de", "it", "es", "ru", "ar"},
				Limit:         limit,
				OnlyNew:       true,
			})
			if err != nil {
				log.Printf("❌ Translation sync failed: %v", err)
				continue
			}

			log.Printf(
				"✅ Translation sync done: seeds=%d affected=%d auto_translated=%d langs=%v",
				result.SeedCount,
				result.AffectedCount,
				result.AutoTranslated,
				result.TargetLangs,
			)
		}
	}()
}

func nextRunAt(now time.Time, hour int) time.Time {
	next := time.Date(now.Year(), now.Month(), now.Day(), hour, 0, 0, 0, now.Location())
	if !next.After(now) {
		next = next.Add(24 * time.Hour)
	}
	return next
}
