package main

import (
	"bssapp-backend/db"
	"bssapp-backend/routes"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"

	"github.com/joho/godotenv"
)

func main() {
	_ = godotenv.Load(".env", "mail.env", ".env.local")

	if err := db.ConnectMSSQL(); err != nil {
		log.Fatalf("mssql connect failed: %v", err)
	}
	pgDB, err := db.ConnectPostgres()
	if err != nil {
		log.Fatalf("postgres connect failed: %v", err)
	}
	defer pgDB.Close()

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

	langs := []string{"en", "de", "it", "es", "ru", "ar"}
	if raw := strings.TrimSpace(os.Getenv("TRANSLATION_SYNC_LANGS")); raw != "" {
		parts := strings.Split(raw, ",")
		custom := make([]string, 0, len(parts))
		for _, p := range parts {
			v := strings.TrimSpace(strings.ToLower(p))
			if v != "" {
				custom = append(custom, v)
			}
		}
		if len(custom) > 0 {
			langs = custom
		}
	}

	autoTranslate := true
	if raw := strings.TrimSpace(strings.ToLower(os.Getenv("TRANSLATION_SYNC_AUTO_TRANSLATE"))); raw != "" {
		if raw == "0" || raw == "false" || raw == "off" {
			autoTranslate = false
		}
	}

	result, err := routes.PerformTranslationSync(pgDB, db.MssqlDB, routes.TranslationSyncOptions{
		AutoTranslate: autoTranslate,
		Languages:     langs,
		Limit:         limit,
		OnlyNew:       true,
	})
	if err != nil {
		log.Fatalf("manual sync failed: %v", err)
	}

	fmt.Printf("translation sync done: seeds=%d affected=%d auto_translated=%d langs=%v\n",
		result.SeedCount,
		result.AffectedCount,
		result.AutoTranslated,
		result.TargetLangs,
	)
}
