using CalledIt.DataAccess;
using CalledIt.Seeder;
using DotNetEnv;
using Microsoft.EntityFrameworkCore;

// Search up the directory tree for .env (works regardless of cwd or run method)
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir != null)
{
    var candidate = Path.Combine(dir.FullName, ".env");
    if (File.Exists(candidate)) { Env.Load(candidate); break; }
    dir = dir.Parent;
}

var connStr = Environment.GetEnvironmentVariable("ConnectionStrings__DefaultConnection");
if (string.IsNullOrEmpty(connStr))
{
    var host = "127.0.0.1";
    var port = "5432";
    var dbName = Environment.GetEnvironmentVariable("DB_NAME") ?? "calleditdb";
    var user = Environment.GetEnvironmentVariable("DB_USER") ?? "calledit";
    var pass = Environment.GetEnvironmentVariable("DB_PASSWORD") ?? "";
    connStr = $"Host={host};Port={port};Database={dbName};Username={user};Password={pass}";
}

var options = new DbContextOptionsBuilder<CalledItDbContext>()
    .UseNpgsql(connStr)
    .Options;

await using var db = new CalledItDbContext(options);

Console.WriteLine("CalledIt Test Data Seeder");
Console.WriteLine($"Database: {connStr.Split(';').FirstOrDefault(p => p.StartsWith("Database", StringComparison.OrdinalIgnoreCase)) ?? connStr}");
Console.WriteLine();

// ---------------------------------------------------------------------------
// Match data source selection
//
// Priority:
//   1. FOOTBALL_DATA_API_KEY env var set → fetch live from football-data.org (single competition)
//   2. Otherwise → load from all *.json files in data/
//
// To use the API directly:
//   export FOOTBALL_DATA_API_KEY=<your-key>
//   export FOOTBALL_DATA_COMPETITION=WC        # optional, defaults to WC
//   export FOOTBALL_DATA_SEASON=2026           # optional, defaults to 2026
// ---------------------------------------------------------------------------

var dataSources = new List<IMatchDataSource>();

var apiKey = Environment.GetEnvironmentVariable("FOOTBALL_DATA_API_KEY");
if (!string.IsNullOrEmpty(apiKey))
{
    var code   = Environment.GetEnvironmentVariable("FOOTBALL_DATA_COMPETITION") ?? "WC";
    var season = Environment.GetEnvironmentVariable("FOOTBALL_DATA_SEASON") ?? "2026";
    Console.WriteLine($"  Source: football-data.org API (competition={code}, season={season})");
    dataSources.Add(new FootballDataApiMatchDataSource(apiKey, code, season));
}
else
{
    var matchesDir = Path.Combine(AppContext.BaseDirectory, "data", "matches");
    foreach (var jsonPath in Directory.GetFiles(matchesDir, "*.json").OrderBy(f => f))
    {
        Console.WriteLine($"  Source: {Path.GetFileName(jsonPath)}");
        dataSources.Add(new JsonFileMatchDataSource(jsonPath));
    }
}

Console.WriteLine();

var uploadsBasePath = Environment.GetEnvironmentVariable("UPLOADS__BASEPATH") ?? "uploads";
var seedDataDir = Path.Combine(AppContext.BaseDirectory, "data");
var logosDir = Path.Combine(seedDataDir, "logos");
var usersJsonPath = Path.Combine(seedDataDir, "users.json");
var seedUsers = !string.Equals(Environment.GetEnvironmentVariable("SEED_USERS"), "false", StringComparison.OrdinalIgnoreCase);
var seedUserCount = int.TryParse(Environment.GetEnvironmentVariable("SEED_USER_COUNT"), out var parsedCount) ? (int?)parsedCount : null;

await TestDataSeeder.SeedAsync(db, dataSources, uploadsBasePath, logosDir, usersJsonPath, seedUsers, seedUserCount);
