package main

import (
	"context"
	"flag"
	"fmt"
	"log/slog"
	"os"
	"time"

	"github.com/TopherMayor/unified-media-manager/internal/db"
	"github.com/TopherMayor/unified-media-manager/internal/migrate"
)

func main() {
	// Flags for each arr database path
	sonarr := flag.String("sonarr", "", "Path to Sonarr SQLite database")
	radarr := flag.String("radarr", "", "Path to Radarr SQLite database")
	sonarrAnime := flag.String("sonarr-anime", "", "Path to Sonarr-anime SQLite database")
	radarrAnime := flag.String("radarr-anime", "", "Path to Radarr-anime SQLite database")
	lidarr := flag.String("lidarr", "", "Path to Lidarr SQLite database")
	readarr := flag.String("readarr", "", "Path to Readarr SQLite database")
	prowlarr := flag.String("prowlarr", "", "Path to Prowlarr SQLite database")
	databaseURL := flag.String("database-url", "", "PostgreSQL connection string (or set DATABASE_URL env)")
	flag.Parse()

	if *databaseURL == "" {
		*databaseURL = os.Getenv("DATABASE_URL")
	}
	if *databaseURL == "" {
		*databaseURL = "postgres://bear:bear123@postgres-shared:5432/umm?sslmode=disable"
	}

	slog.Info("starting UMM arr data migration tool")

	// Connect to PostgreSQL
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	database, err := db.New(ctx, *databaseURL)
	cancel()
	if err != nil {
		slog.Error("failed to connect to database", "error", err)
		os.Exit(1)
	}
	defer database.Close()

	// Run schema migrations to ensure tables exist
	if err := database.RunMigrations(context.Background(), db.MigrationsFS); err != nil {
		slog.Error("failed to run migrations", "error", err)
		os.Exit(1)
	}

	sources := migrate.ArrSources{
		Sonarr:      *sonarr,
		Radarr:      *radarr,
		SonarrAnime: *sonarrAnime,
		RadarrAnime: *radarrAnime,
		Lidarr:      *lidarr,
		Readarr:     *readarr,
		Prowlarr:    *prowlarr,
	}

	m := migrate.NewMigrator(database, sources)
	report, err := m.Run(context.Background())
	if err != nil {
		slog.Error("migration failed", "error", err)
		fmt.Println()
		fmt.Println(report.String())
		os.Exit(1)
	}

	fmt.Println()
	fmt.Println(report.String())
}
