using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using CounterDrone.Core.Models;
using CounterDrone.Core.Repository;
using CounterDrone.Core.Services;
using SQLite;

namespace CounterDrone.Core
{
    /// <summary>数据库管理器 — 建表 / 连接管理</summary>
    public class DatabaseManager
    {
        private readonly IPathProvider _paths;

        public DatabaseManager(IPathProvider paths)
        {
            _paths = paths;
        }

        /// <summary>初始化主数据库（建表 + 种子数据）</summary>
        public SQLiteConnection OpenMainDb()
        {
            var dbPath = _paths.GetMainDbPath();
            var db = new SQLiteConnection(dbPath);
            CreateMainTables(db);
            SeedDefaultData(db);
            SeedDefaultScenarios(db);
            return db;
        }

        /// <summary>创建/打开任务帧数据库</summary>
        public SQLiteConnection OpenFrameDb(string taskId)
        {
            var dbPath = Path.Combine(_paths.GetFramesDir(), $"{taskId}.db");
            var db = new SQLiteConnection(dbPath);
            db.CreateTable<SimFrameRecord>();
            db.CreateIndex("SimFrameRecord", new[] { "TaskId", "FrameIndex" });
            return db;
        }

        /// <summary>删除任务帧数据库文件</summary>
        public void DeleteFrameDb(string taskId)
        {
            var dbPath = Path.Combine(_paths.GetFramesDir(), $"{taskId}.db");
            if (File.Exists(dbPath))
                File.Delete(dbPath);
        }

        private void SeedDefaultData(SQLiteConnection db)
        {
            db.CreateTable<MetaEntry>();

            var defaults = DefaultData.Load(_paths);
            var currentVersion = db.Table<MetaEntry>()
                .FirstOrDefault(m => m.Key == "defaultsVersion")?.Value;

            // 版本未变且数据已存在 → 跳过
            if (currentVersion == defaults.Version && db.Table<AmmunitionSpec>().Count() > 0)
                return;

            // 插入或更新默认数据（按 Id 覆盖，不删除用户自建数据）
            foreach (var a in defaults.Ammunition) db.InsertOrReplace(a);

            db.InsertOrReplace(new MetaEntry { Key = "defaultsVersion", Value = defaults.Version });
        }

        private void SeedDefaultScenarios(SQLiteConnection db)
        {
            var currentVersion = db.Table<MetaEntry>()
                .FirstOrDefault(m => m.Key == "scenariosVersion")?.Value;

            // 版本未变 → 跳过
            if (currentVersion == "2") return;

            var defaults = DefaultData.Load(_paths);
            var scenario = new ScenarioService(
                new SimTaskRepository(db), new CombatSceneRepository(db),
                new ControlZoneRepository(db), new TargetConfigRepository(db),
                new EquipmentDeploymentRepository(db), new CloudDispersalRepository(db),
                new RoutePlanRepository(db), new WaypointRepository(db));

            DefaultScenarios.Seed(scenario, defaults);

            db.InsertOrReplace(new MetaEntry { Key = "scenariosVersion", Value = "2" });
        }

        private void CreateMainTables(SQLiteConnection db)
        {
            db.CreateTable<ModelInfo>();
            db.CreateTable<AmmunitionSpec>();
            db.CreateTable<SimTask>();
            db.CreateTable<CombatScene>();
            db.CreateTable<ControlZone>();
            db.CreateTable<TargetConfig>();
            db.CreateTable<EquipmentDeployment>();
            db.CreateTable<CloudDispersal>();
            db.CreateTable<RoutePlan>();
            db.CreateIndex("RoutePlan", new[] { "TaskId", "WaveId" }, true);
            db.CreateTable<Waypoint>();
            db.CreateTable<SimulationReport>();

            db.CreateIndex("SimTask", "TaskNumber");
            db.CreateIndex("ControlZone", "TaskId");
            db.CreateIndex("TargetConfig", "TaskId");
            db.CreateIndex("EquipmentDeployment", "TaskId");
            db.CreateIndex("Waypoint", "TaskId");
            db.CreateIndex("SimulationReport", "TaskId");
        }
    }
}
