package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	_ "github.com/go-sql-driver/mysql"

	"lingniu/vehicle-data-platform/apps/api/internal/platform"
)

func main() {
	if err := run(); err != nil {
		log.Printf("reconciliation evaluation failed: %v", err)
		os.Exit(1)
	}
}

func run() error {
	dsn := strings.TrimSpace(os.Getenv("MYSQL_DSN"))
	if dsn == "" {
		return fmt.Errorf("MYSQL_DSN is required")
	}
	timeout := 5 * time.Minute
	if value := strings.TrimSpace(os.Getenv("RECONCILIATION_TIMEOUT_SEC")); value != "" {
		parsed, err := time.ParseDuration(value + "s")
		if err != nil || parsed < 10*time.Second || parsed > 30*time.Minute {
			return fmt.Errorf("RECONCILIATION_TIMEOUT_SEC must be between 10 and 1800 seconds")
		}
		timeout = parsed
	}
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()
	db, err := platform.OpenSQL(ctx, "mysql", dsn)
	if err != nil {
		return fmt.Errorf("connect mysql: %w", err)
	}
	defer db.Close()
	service := platform.NewService(platform.NewProductionStore(db, nil, ""))
	started := time.Now()
	result, err := service.EvaluateReconciliation(ctx)
	if err != nil {
		return err
	}
	log.Printf(
		"reconciliation evaluation completed run=%s detected=%d new=%d active=%d recovered=%d rules=%v duration=%s",
		result.RunID, result.Detected, result.New, result.Active, result.Recovered, result.RuleCounts, time.Since(started),
	)
	return nil
}
