using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using CounterDrone.Core.Models;
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);
            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)
        {
            if (db.Table<AmmunitionSpec>().Count() > 0) return;

            var jsonPath = Path.Combine(_paths.GetDataRoot(), "default_ammo.json");
            if (!File.Exists(jsonPath)) return;

            var specs = JsonSerializer.Deserialize<List<AmmunitionSpec>>(File.ReadAllText(jsonPath));
            if (specs != null)
                foreach (var s in specs) db.Insert(s);
        }

        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", "GroupId" }, true);
            db.CreateTable<Waypoint>();
            db.CreateTable<Group>();
            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");
        }
    }
}
