using System;
using System.Threading;
using System.Threading.Tasks;
using Npgsql;
using KArtSell.BuildingBlocks.Time;

class MonitorJob893
{
    static async Task Main(string[] args)
    {
        var connectionString = "Host=localhost;Port=5432;Database=kartsell;Username=kartsell;Password=kartsell";
        var monitoringInterval = TimeSpan.FromMinutes(5);
        var clock = new SystemClock();

        Console.WriteLine("=== Job 893 Phase 1 Monitor ===");
        Console.WriteLine($"Interval: {monitoringInterval.TotalMinutes} minutes");
        Console.WriteLine($"Started: {clock.UtcNow:yyyy-MM-dd HH:mm:ss}");
        Console.WriteLine();

        int checkCount = 0;

        while (true)
        {
            checkCount++;
            try
            {
                await using var connection = new NpgsqlConnection(connectionString);
                await connection.OpenAsync();

                const string query = @"
                    SELECT
                        job_id,
                        model_id,
                        status,
                        window_start,
                        window_end,
                        progress_percent,
                        rows_processed,
                        created_at,
                        updated_at,
                        last_error
                    FROM model_operations.shadow_runs
                    WHERE job_id = '00000000-0000-0000-0000-000000000893'
                    LIMIT 1;";

                await using var cmd = connection.CreateCommand();
                cmd.CommandText = query;

                await using var reader = await cmd.ExecuteReaderAsync();

                Console.WriteLine($"[{checkCount}] {clock.UtcNow:yyyy-MM-dd HH:mm:ss}");

                if (await reader.ReadAsync())
                {
                    var status = reader.GetString(2);
                    var progress = reader.GetInt32(5);
                    var rowsProcessed = reader.GetInt64(6);
                    var updatedAt = reader.GetDateTime(8);
                    var lastError = reader.IsDBNull(9) ? "None" : reader.GetString(9);

                    Console.WriteLine($"  Status: {status}");
                    Console.WriteLine($"  Progress: {progress}%");
                    Console.WriteLine($"  Rows: {rowsProcessed:N0}");
                    Console.WriteLine($"  Updated: {updatedAt:HH:mm:ss}");
                    Console.WriteLine($"  Error: {lastError}");

                    if (status == "Completed" || status == "Failed")
                    {
                        Console.WriteLine($"\n✅ Job 893 {status.ToLower()}");
                        break;
                    }
                }
                else
                {
                    Console.WriteLine("  (Job 893 not found)");
                }

                await connection.CloseAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"  ❌ Error: {ex.Message}");
            }

            Console.WriteLine();

            if (args.Length > 0 && args[0] == "--once")
                break;

            await Task.Delay(monitoringInterval);
        }
    }
}
