using BLL.Interfaces;
using BLL.Services;
using CONTROLLER;
using CONTROLLER.Configurations;
using CONTROLLER.Middleware;
using DAL.Interfaces;
using DAL.Repositories;
using DinkToPdf;
using MDL.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using Amazon.S3;
using System;
using System.IO;

// 首先输出控制台信息，确保即使Serilog配置失败也能看到启动信息
Console.WriteLine($"[{DateTime.Now}] Application starting...");
Console.WriteLine($"[{DateTime.Now}] Environment: {Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}");
Console.WriteLine($"[{DateTime.Now}] Current Directory: {Directory.GetCurrentDirectory()}");

var builder = WebApplication.CreateBuilder(args);

// 输出构建器环境信息
Console.WriteLine($"[{DateTime.Now}] Builder Environment: {builder.Environment.EnvironmentName}");
Console.WriteLine($"[{DateTime.Now}] Content Root Path: {builder.Environment.ContentRootPath}");

// 加载配置文件，包括本地覆盖配置
Console.WriteLine($"[{DateTime.Now}] Loading configuration files...");
try
{
    builder.Configuration
        .SetBasePath(builder.Environment.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.Development.json", optional: true, reloadOnChange: true) // Development  Production
        //.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
        //.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables();
    
    Console.WriteLine($"[{DateTime.Now}] Configuration files loaded successfully");
}
catch (Exception ex)
{
    Console.WriteLine($"[{DateTime.Now}] ERROR loading configuration: {ex.Message}");
}

// 绑定配置到模型
Console.WriteLine($"[{DateTime.Now}] Binding configuration to model...");
AppSettings appSettings;
try
{
    appSettings = builder.Configuration.Get<AppSettings>() ?? new AppSettings();
    builder.Services.AddSingleton(appSettings);
    Console.WriteLine($"[{DateTime.Now}] Configuration bound successfully");
}
catch (Exception ex)
{
    Console.WriteLine($"[{DateTime.Now}] ERROR binding configuration: {ex.Message}");
    appSettings = new AppSettings();
    builder.Services.AddSingleton(appSettings);
}

// 配置Serilog，从appsettings.json读取配置
Console.WriteLine($"[{DateTime.Now}] Configuring Serilog...");
try
{
    builder.Host.UseSerilog((context, configuration) =>
    {
        try
        {
            configuration.ReadFrom.Configuration(context.Configuration)
                        .WriteTo.Console(); // 确保输出到控制台
            Console.WriteLine($"[{DateTime.Now}] Serilog configured from appsettings.json");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"[{DateTime.Now}] ERROR configuring Serilog from config: {ex.Message}");
            // 回退到基本配置
            configuration.MinimumLevel.Information()
                        .WriteTo.Console()
                        .WriteTo.File("logs/fallback_log-.txt", rollingInterval: RollingInterval.Day);
            Console.WriteLine($"[{DateTime.Now}] Serilog fallback configuration applied");
        }
    });
    
    Console.WriteLine($"[{DateTime.Now}] Serilog configured successfully");
}
catch (Exception ex)
{
    Console.WriteLine($"[{DateTime.Now}] ERROR configuring Serilog: {ex.Message}");
}

// 记录环境信息
Console.WriteLine($"[{DateTime.Now}] Logging environment information...");
try
{
    Serilog.Log.Information("Application starting with Environment: {Environment}", builder.Environment.EnvironmentName);
    Serilog.Log.Information("Content Root Path: {ContentRoot}", builder.Environment.ContentRootPath);
    Serilog.Log.Information("Web Root Path: {WebRoot}", builder.Environment.WebRootPath);
    Serilog.Log.Information("Is Development: {IsDevelopment}", builder.Environment.IsDevelopment());
    Serilog.Log.Information("Is Production: {IsProduction}", builder.Environment.IsProduction());
}
catch (Exception ex)
{
    Console.WriteLine($"[{DateTime.Now}] ERROR logging with Serilog: {ex.Message}");
}

// 记录配置文件加载信息
var envConfigFile = $"appsettings.{builder.Environment.EnvironmentName}.json";
Console.WriteLine($"[{DateTime.Now}] Loading configuration files:");
Console.WriteLine($"[{DateTime.Now}] - appsettings.json");
Console.WriteLine($"[{DateTime.Now}] - {envConfigFile}");

try
{
    Serilog.Log.Information("Loading configuration files:");
    Serilog.Log.Information("- appsettings.json");
    Serilog.Log.Information($"- {envConfigFile}");
}
catch { }

// 记录数据库连接字符串信息
Console.WriteLine($"[{DateTime.Now}] Checking database connection string...");
try
{
    var connectionString = builder.Configuration.GetConnectionString("Default");
    if (!string.IsNullOrEmpty(connectionString))
    {
        // 隐藏密码部分
        var maskedConnectionString = System.Text.RegularExpressions.Regex.Replace(connectionString, @"password=.*?;", "password=***;");
        Console.WriteLine($"[{DateTime.Now}] Database connection string loaded: {maskedConnectionString}");
        Serilog.Log.Information("Database connection string loaded: {ConnectionString}", maskedConnectionString);
    }
    else
    {
        Console.WriteLine($"[{DateTime.Now}] WARNING: No database connection string found in configuration");
        Serilog.Log.Warning("No database connection string found in configuration");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"[{DateTime.Now}] ERROR reading connection string: {ex.Message}");
}

// 记录日志配置信息
Console.WriteLine($"[{DateTime.Now}] Checking logging configuration...");
try
{
    var logLevel = builder.Configuration.GetValue<string>("Serilog:MinimumLevel:Default");
    var logPath = builder.Configuration.GetValue<string>("Serilog:WriteTo:0:Args:path");
    Console.WriteLine($"[{DateTime.Now}] Logging configuration:");
    Console.WriteLine($"[{DateTime.Now}] - Minimum Log Level: {logLevel}");
    Console.WriteLine($"[{DateTime.Now}] - Log File Path: {logPath}");
    
    Serilog.Log.Information("Logging configuration:");
    Serilog.Log.Information("- Minimum Log Level: {LogLevel}", logLevel);
    Serilog.Log.Information("- Log File Path: {LogPath}", logPath);
}
catch (Exception ex)
{
    Console.WriteLine($"[{DateTime.Now}] ERROR reading logging configuration: {ex.Message}");
}

// 配置CORS
// builder.Services.AddCors(options =>
// {
//     options.AddDefaultPolicy(builder =>
//     {
//         builder.AllowAnyOrigin()
//                .AllowAnyMethod()
//                .AllowAnyHeader();
//     });
// });

// 配置线程池
Console.WriteLine($"[{DateTime.Now}] Configuring thread pool...");
try
{
    // 设置最小工作线程数
    System.Threading.ThreadPool.SetMinThreads(100, 100);
    // 设置最大工作线程数
    System.Threading.ThreadPool.SetMaxThreads(1000, 1000);
    Console.WriteLine($"[{DateTime.Now}] Thread pool configured successfully");
}
catch (Exception ex)
{
    Console.WriteLine($"[{DateTime.Now}] ERROR configuring thread pool: {ex.Message}");
}

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase;
    });
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddHttpClient(); // 注册IHttpClientFactory服务
// 添加健康检查服务
builder.Services.AddHealthChecks();

// DI registrations
builder.Services.AddScoped<ITagReplacing, TagService>();
builder.Services.AddScoped<ITagRepository, TagRepository>();
builder.Services.AddScoped<ITagParsing, TagParsingService>();
builder.Services.AddScoped<ITagValidation, TagValidationService>();
builder.Services.AddScoped<ILogisticsParser, LogisticsParserService>();
builder.Services.AddScoped<ILabelReplaceRepository, LabelReplaceRepository>();
builder.Services.AddScoped<ILabelReplaceService, BLL.Services.LabelReplaceService>();
builder.Services.AddScoped<ILabelScanRepository, LabelScanRepository>();
builder.Services.AddScoped<ILabelScanService, BLL.Services.LabelScanService>();
builder.Services.AddScoped<ICustomerRepository, CustomerRepository>();
builder.Services.AddScoped<ICustomerApiRepository, CustomerApiRepository>();
builder.Services.AddScoped<ICargoDataRepository, CargoDataRepository>();
builder.Services.AddScoped<IExcelImportService, ExcelImportService>();
builder.Services.AddScoped<IBagTagRepository, BagTagRepository>();
builder.Services.AddScoped<IBagTagService, BagTagService>();
// 到货交接单和出货交接单依赖注入
builder.Services.AddScoped<IArrivalHandoverFormRepository, ArrivalHandoverFormRepository>();
builder.Services.AddScoped<IArrivalHandoverFormService, ArrivalHandoverFormService>();
builder.Services.AddScoped<IArrivalScanRecordRepository, ArrivalScanRecordRepository>();
builder.Services.AddScoped<IShippingHandoverFormRepository, ShippingHandoverFormRepository>();
builder.Services.AddScoped<IShippingHandoverFormService, ShippingHandoverFormService>();
// 出货交接单与袋牌关联依赖注入
builder.Services.AddScoped<IShippingHandoverFormBagTagRepository, ShippingHandoverFormBagTagRepository>();
builder.Services.AddScoped<IShippingHandoverFormBagTagService, ShippingHandoverFormBagTagService>();

// 标签模块依赖注入
builder.Services.AddMemoryCache();
builder.Services.AddScoped<ICacheService, MemoryCacheService>();
builder.Services.AddScoped<ITagTemplateRepository, TagTemplateRepository>();
builder.Services.AddScoped<ITagInstanceRepository, TagInstanceRepository>();
builder.Services.AddScoped<ITagTemplateService, TagTemplateService>();
builder.Services.AddScoped<ITagInstanceService, TagInstanceService>();
builder.Services.AddScoped<ITagTriggerService, TagTriggerService>();
builder.Services.AddScoped<ITagGenerationService, TagGenerationService>();
builder.Services.AddScoped<IMetricsCalculationService, MetricsCalculationService>();

builder.Services.AddScoped<IOrderLogRepository, OrderLogRepository>();
builder.Services.AddScoped<IOrderLogService, OrderLogService>();

// PDF缓存服务注册
builder.Services.AddScoped<ILabelPdfCacheRepository, LabelPdfCacheRepository>();
builder.Services.AddScoped<ILabelPdfCacheService, LabelPdfCacheService>();
// 注册PDF缓存定时任务
builder.Services.AddHostedService<CONTROLLER.BackgroundServices.LabelPdfCacheBackgroundService>();

// Amazon S3 服务注册
builder.Services.AddAWSService<IAmazonS3>();

// SqlSugar registration (using configuration)
var mySqlConn = builder.Configuration.GetConnectionString("Default") ?? "";
builder.Services.AddSingleton<DB.Database.ISqlSugarProvider>(sp => new DB.Database.SqlSugarProvider(mySqlConn));
// Kestrel服务器配置优化
//builder.WebHost.ConfigureKestrel(serverOptions =>
//{
//    serverOptions.Limits.MaxConcurrentConnections = 1000;
//    serverOptions.Limits.MaxConcurrentUpgradedConnections = 1000;
//    serverOptions.Limits.MinRequestBodyDataRate = 
//        new Microsoft.AspNetCore.Server.Kestrel.Core.MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
//    serverOptions.Limits.MaxRequestBodySize = 10 * 1024 * 1024; // 10MB
//});
builder.WebHost.ConfigureKestrel(options =>
{
    options.Limits.MaxConcurrentConnections = 10000; // 公网建议设硬上限
    options.Limits.MaxConcurrentUpgradedConnections = 10000;
    options.Limits.MinRequestBodyDataRate = new Microsoft.AspNetCore.Server.Kestrel.Core.MinDataRate(bytesPerSecond: 1024, gracePeriod: TimeSpan.FromSeconds(10));
    options.Limits.MinResponseDataRate = new Microsoft.AspNetCore.Server.Kestrel.Core.MinDataRate(bytesPerSecond: 1024, gracePeriod: TimeSpan.FromSeconds(10));
    options.Limits.MaxRequestBodySize = 10 * 1024 * 1024; // 10MB，避免大文件上传风险
    options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2); // 保持连接超时
    options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(30); // 请求头接收超时
    options.Limits.Http2.MaxStreamsPerConnection = 300; // 单连接并发流数
    options.Limits.Http2.HeaderTableSize = 4096; // HPACK 压缩表大小
    options.Limits.Http2.InitialConnectionWindowSize = 131_072; // 连接级流量窗口
    options.AllowSynchronousIO = false;
});

//DateTime utcTime = DateTime.UtcNow.AddHours(-5);

//TimeZoneInfo easternTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
//TimeSpan baseOffset = easternTimeZone.BaseUtcOffset;
//Console.WriteLine($"基础标准偏移：UTC{baseOffset.Hours:+0;-#}");

//TimeSpan currentOffset = easternTimeZone.GetUtcOffset(DateTime.UtcNow);
//Console.WriteLine($"{currentOffset.Hours:+0;-#}");

builder.Services.AddResponseCompression(options =>
{
    options.EnableForHttps = true;
    options.MimeTypes = Microsoft.AspNetCore.ResponseCompression.ResponseCompressionDefaults.MimeTypes.Concat(
        new[] { "application/pdf", "application/octet-stream" });
});

var app = builder.Build();
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseMiddleware<RequestTrackingMiddleware>();
app.UseResponseCompression();

// 使用CORS中间件
// app.UseCors();

app.MapControllers();
// 添加健康检查端点
app.MapHealthChecks("/health");
// Bind to all network interfaces on port 5003
app.Run("http://*:5003");

// 从环境变量读取部署实例配置（蓝或绿）
//var deploymentInstance = Environment.GetEnvironmentVariable("DEPLOYMENT_INSTANCE") ?? "blue";
//var port = deploymentInstance.ToLower() == "green" ? 5001 : 5000;

//Console.WriteLine($"[{DateTime.Now}] Deployment Instance: {deploymentInstance}");
//Console.WriteLine($"[{DateTime.Now}] Listening on port: {port}");
//Serilog.Log.Information("Deployment Instance: {Instance}, Port: {Port}", deploymentInstance, port);

//// 配置优雅关闭
//var shutdownTimeout = TimeSpan.FromSeconds(
//    int.TryParse(Environment.GetEnvironmentVariable("SHUTDOWN_TIMEOUT"), out var timeout) ? timeout : 30
//);

//Console.WriteLine($"[{DateTime.Now}] Shutdown timeout configured: {shutdownTimeout.TotalSeconds} seconds");

//// 处理应用关闭事件，等待现有请求完成
//var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
//lifetime.ApplicationStopping.Register(() =>
//{
//    Console.WriteLine($"[{DateTime.Now}] Application shutdown requested...");
//    Serilog.Log.Information("Application shutdown requested. Waiting for requests to complete...");

//    Task.Run(async () =>
//    {
//        try
//        {
//            await Task.Delay(shutdownTimeout);
//            Console.WriteLine($"[{DateTime.Now}] Shutdown timeout reached, forcing exit");
//            Serilog.Log.Warning("Shutdown timeout reached after {Timeout} seconds", shutdownTimeout.TotalSeconds);
//        }
//        catch (Exception ex)
//        {
//            Console.WriteLine($"[{DateTime.Now}] Error during shutdown: {ex.Message}");
//            Serilog.Log.Error(ex, "Error during graceful shutdown");
//        }
//    });
//});

//// 添加版本信息端点
//app.MapGet("/api/version", () => Results.Ok(new 
//{ 
//    version = "1.0.0", 
//    instance = deploymentInstance,
//    port = port,
//    buildTime = DateTime.Now,
//    timestamp = DateTime.UtcNow
//}));

//// 增强的健康检查端点，包含更多信息
//app.MapGet("/api/health", () => 
//{
//    var healthInfo = new
//    {
//        status = "healthy",
//        instance = deploymentInstance,
//        port = port,
//        timestamp = DateTime.UtcNow,
//        uptime = DateTime.Now,
//        environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
//    };
//    return Results.Ok(healthInfo);
//});

//// Bind to all network interfaces on the configured port
//app.Run($"http://*:{port}");
//app.Run();
