using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Pomelo.EntityFrameworkCore.MySql;
using Haoliang.Core.Services;
using Haoliang.Api.Middleware;
using Haoliang.Data.Entities;
using Haoliang.Data.Repositories;

namespace Haoliang.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "CNC Data Collection API", Version = "v1" });
            });

            // 配置跨域
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll", builder =>
                {
                    builder.AllowAnyOrigin()
                           .AllowAnyMethod()
                           .AllowAnyHeader();
                });
            });

            // 配置SignalR
            services.AddSignalR();

            // 配置服务依赖注入
            ConfigureServices(services);
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "CNC Data Collection API v1"));
            }

            // 中间件顺序很重要
            app.UseMiddleware<LoggingMiddleware>();
            app.UseMiddleware<CORSMiddleware>();
            app.UseMiddleware<ExceptionMiddleware>();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<RealTimeHub>("/realtime");
            });
        }

        private void ConfigureServices(IServiceCollection services)
        {
            // 配置数据库连接
            var connectionString = Configuration.GetConnectionString("DefaultConnection");
            var businessConnectionString = Configuration.GetConnectionString("BusinessDbConnection");
            
            // 业务数据库配置
            if (!string.IsNullOrEmpty(businessConnectionString))
            {
                services.AddDbContext<CNCBusinessDbContext>(options =>
                    options.UseMySql(businessConnectionString, 
                        ServerVersion.AutoDetect(businessConnectionString),
                        mysqlOptions => mysqlOptions.EnableRetryOnFailure(
                            maxRetryCount: 3,
                            maxRetryDelay: TimeSpan.FromSeconds(30),
                            errorNumbersToAdd: null)));
            }

            // 日志数据库配置
            var logConnectionString = Configuration.GetConnectionString("LogDbConnection");
            if (!string.IsNullOrEmpty(logConnectionString))
            {
                services.AddDbContext<CNCLLogDbContext>(options =>
                    options.UseMySql(logConnectionString, 
                        ServerVersion.AutoDetect(logConnectionString),
                        mysqlOptions => mysqlOptions.EnableRetryOnFailure(
                            maxRetryCount: 3,
                            maxRetryDelay: TimeSpan.FromSeconds(30),
                            errorNumbersToAdd: null)));
            }

            // 注册主要数据库上下文（用于业务操作）
            services.AddDbContext<CNCBusinessDbContext>(options =>
                options.UseMySql(connectionString, 
                    ServerVersion.AutoDetect(connectionString),
                    mysqlOptions => mysqlOptions.EnableRetryOnFailure(
                        maxRetryCount: 3,
                        maxRetryDelay: TimeSpan.FromSeconds(30),
                        errorNumbersToAdd: null)));

            // 配置数据库连接池
            services.AddDbContextPool<CNCBusinessDbContext>(options =>
                options.UseMySql(connectionString, 
                    ServerVersion.AutoDetect(connectionString),
                    mysqlOptions => mysqlOptions.EnableRetryOnFailure(
                        maxRetryCount: 3,
                        maxRetryDelay: TimeSpan.FromSeconds(30),
                        errorNumbersToAdd: null)));

            // 配置内存缓存
            services.AddMemoryCache();
            services.AddDistributedMemoryCache();

            // 注册缓存服务
            services.AddSingleton<ICacheService, MemoryCacheService>();

            // 注册状态机服务
            services.AddHostedService<DeviceStateMachine>();

            // 注册服务
            services.AddScoped<IDeviceCollectionService, DeviceCollectionService>();
            services.AddScoped<IProductionService, ProductionService>();
            services.AddScoped<IProductionCalculator, ProductionCalculator>();
            services.AddScoped<IProductionScheduler, ProductionScheduler>();
            services.AddScoped<IAlarmService, AlarmManager>();
            services.AddScoped<IAlarmRuleService, AlarmRuleService>();
            services.AddScoped<IAlarmNotificationService, AlarmNotificationService>();
            services.AddScoped<ITemplateService, TemplateManager>();
            services.AddScoped<ITagMappingService, TagMappingService>();
            services.AddScoped<ITemplateValidationService, TemplateValidationService>();
            services.AddScoped<ITemplateMigrationService, TemplateMigrationService>();
            services.AddScoped<ILoggerService, ConsoleLoggerService>();
            services.AddScoped<ICacheService, MemoryCacheService>();
            services.AddScoped<IRealTimeService, RealTimeService>();
            services.AddScoped<IProductionStatisticsService, ProductionStatisticsService>();
            services.AddScoped<IRulesService, RulesService>();
            
            // 注册配置服务
            services.AddScoped<ISystemService, SystemService>();
            services.AddScoped<ISystemConfigService, SystemConfigService>();
            
            // 注册中间件服务
            services.AddScoped<IDeviceStateMachine, DeviceStateMachine>();
            
            // 注册后台任务服务
            services.AddHostedService<BackgroundTaskService>();

            // 注册仓储
            services.AddScoped<IDeviceRepository, DeviceRepository>();
            services.AddScoped<ITemplateRepository, TemplateRepository>();
            services.AddScoped<IProductionRepository, ProductionRepository>();
            services.AddScoped<IProgramProductionSummaryRepository, ProgramProductionSummaryRepository>();
            services.AddScoped<IProductionSummaryRepository, ProductionSummaryRepository>();
            services.AddScoped<IAlarmRepository, AlarmRepository>();
            services.AddScoped<IAlarmRuleRepository, AlarmRuleRepository>();
            services.AddScoped<IAlarmNotificationRepository, AlarmNotificationRepository>();
            services.AddScoped<ISystemRepository, SystemRepository>();
            services.AddScoped<ISystemConfigRepository, SystemConfigRepository>();
            services.AddScoped<ICollectionTaskRepository, CollectionTaskRepository>();
            services.AddScoped<ICollectionResultRepository, CollectionResultRepository>();
            services.AddScoped<ICollectionLogRepository, CollectionLogRepository>();
            services.AddScoped<ILogRepository, LogRepository>();
            services.AddScoped<IUserRepository, UserRepository>();
            services.AddScoped<IAlarmNotificationRepository, AlarmNotificationRepository>();
            services.AddScoped<ITagMappingRepository, TagMappingRepository>();
            
            // 注册设备状态相关仓储
            services.AddScoped<IDeviceStatusRepository, DeviceStatusRepository>();
            
            // 注册Ping服务
            services.AddScoped<IPingService, PingService>();
            
            // 注册数据解析和存储服务
            services.AddScoped<IDataParserService, DataParserService>();
            services.AddScoped<IDataStorageService, DataStorageService>();
            services.AddScoped<IRetryService, RetryService>();

            // 注册SignalR Hub
            services.AddSingleton<RealTimeHub>();
        }
    }
}