using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

namespace SHH.CameraSdk;

public class Program
{
    [STAThread]
    public static async Task Main(string[] args)
    {
        // 1. 身份识别与端口计算
        int processId = 1;
        if (args.Length > 0 && int.TryParse(args[0], out int pid)) processId = pid;
        int port = 5000 + (processId - 1);

        Console.Title = $"SHH Gateway - Instance #{processId} (Port: {port})";

        // 2. 硬件预热 (静态方法保留)
        InitHardwareEnv();

        // 3. 创建 WebHost 并加载 SDK
        var builder = WebApplication.CreateBuilder(args);

        // ★★★★★ 核心变化：调用扩展方法加载 SDK ★★★★★
        // 这行代码把 MemoryCache、CameraManager、流水线全部配好了
        builder.Services.AddCameraSdk(processId);

        // 4. 配置 Web 相关的服务 (Swagger, Controllers, CORS)
        ConfigureWebServices(builder, processId);

        var app = builder.Build();

        // 5. 配置中间件管道
        ConfigureMiddleware(app, processId);

        // 6. 启动业务逻辑
        await StartBusinessLogic(app);

        // 7. 启动 Web 监听
        _ = app.RunAsync($"http://0.0.0.0:{port}");
        Console.WriteLine($"[System] 网关 #{processId} 就绪。地址: http://localhost:{port}");

        // 8. 阻塞驻留
        Console.WriteLine(">> 按 'S' 键退出...");
        while (Console.ReadKey(true).Key != ConsoleKey.S) { Thread.Sleep(100); }

        Console.WriteLine("[System] 正在停机...");
        await app.StopAsync();
    }

    // --- 下面是拆分出来的私有辅助方法，让 Main 看起来更清晰 ---

    static void ConfigureWebServices(WebApplicationBuilder builder, int processId)
    {
        // CORS
        builder.Services.AddCors(options =>
        {
            options.AddPolicy("AllowAll", p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
        });

        // Controllers & Filters
        builder.Services.AddControllers(options =>
        {
            options.Filters.Add<UserActionFilter>();
        });

        // Swagger
        builder.Services.AddEndpointsApiExplorer();
        builder.Services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = $"SHH Gateway #{processId}", Version = "v1" });
        });
    }

    static void ConfigureMiddleware(WebApplication app, int processId)
    {
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", $"Gateway {processId}"));
        app.UseCors("AllowAll");
        app.MapControllers();
    }

    static async Task StartBusinessLogic(WebApplication app)
    {
        // 从 DI 容器中获取已经注册好的服务
        var cameraManager = app.Services.GetRequiredService<CameraManager>();

        // 必须显式获取一次 Sentinel 确保它被实例化并开始工作
        var sentinel = app.Services.GetRequiredService<ConnectivitySentinel>();

        // 启动相机的加载逻辑
        await cameraManager.StartAsync();

        // 添加测试设备 (原有逻辑)
        await AddTestDevices(cameraManager);
    }

    static void InitHardwareEnv()
    {
        Console.WriteLine("[硬件] 海康驱动预热中...");
        HikNativeMethods.NET_DVR_Init();
        HikSdkManager.ForceWarmUp();
        DahuaSdkManager.ForceWarmUp();
    }

    static async Task AddTestDevices(CameraManager manager)
    {
        try
        {
            // ... 这里保留你原本的添加测试设备代码 ...
            // var config = new VideoSourceConfig { ... }
            // manager.AddDevice(config);
        }
        catch { }
    }
}