using System.Collections.Generic;
using CounterDrone.Core;
using CounterDrone.Core.Models;
using CounterDrone.Core.Repository;
using CounterDrone.Core.Services;
using UnityEngine;

namespace CounterDrone.Unity
{
    /// <summary>想定管理桥接 — 仿真任务 CRUD、5 步配置保存、搜索分页</summary>
    public class ScenarioManager : MonoBehaviour
    {
        private IScenarioService _service;
        private SQLite.SQLiteConnection _db;
        private IDataService _dataService;

        public IScenarioService Service => _service;
        public IDataService DataService => _dataService;

        public void Awake()
        {
            try
            {
                var paths = new UnityPathProvider();
                Debug.Log($"ScenarioManager.Awake: dbPath={paths.GetMainDbPath()}");
                _db = new DatabaseManager(paths).OpenMainDb();
                SqliteConnectionTracker.Track(_db);
                _service = new ScenarioService(
                    new ScenarioRepository(_db), new CombatSceneRepository(_db),
                    new ControlZoneRepository(_db), new ScenarioDroneRepository(_db),
                    new ScenarioUnitRepository(_db), new CloudDispersalRepository(_db),
                    new RoutePlanRepository(_db), new WaypointRepository(_db));
                _dataService = new DataService(
                    new AmmunitionSpecRepository(_db), new FireUnitSpecRepository(_db),
                    new DroneSpecRepository(_db), new SensorSpecRepository(_db),
                    new EnvironmentSpecRepository(_db), new FormationTemplateRepository(_db),
                    new RouteTemplateRepository(_db));
                Debug.Log("ScenarioManager.Awake: OK");
            }
            catch (System.Exception ex)
            {
                Debug.LogError($"ScenarioManager.Awake FAILED: {ex}");
            }
        }

        void OnDisable() { SqliteConnectionTracker.Untrack(_db); _db?.Dispose(); _db = null; }

        public Scenario CreateScenario(string name, string number) => _service.CreateScenario(name, number);
        public void DeleteScenario(string id) => _service.DeleteScenario(id);
        public Scenario UpdateScenario(Scenario s) => _service.UpdateScenario(s);
        public ScenarioConfig GetDetail(string id) => _service.GetScenarioDetail(id);
        public PagedResult<Scenario> Search(string kw, string from, string to, int page, int size)
            => _service.SearchScenarios(kw, from, to, page, size);

        public void SaveScene(string scenarioId, CombatScene s) => _service.SaveScene(scenarioId, s);
        public CombatScene GetScene(string scenarioId) => _service.GetScene(scenarioId);

        public void SaveControlZones(string scenarioId, List<ControlZone> z) => _service.SaveControlZones(scenarioId, z);
        public List<ControlZone> GetControlZones(string scenarioId) => _service.GetControlZones(scenarioId);
        public void DeleteControlZone(string id) => _service.DeleteControlZone(id);

        public ScenarioDrone SaveScenarioDrone(string scenarioId, ScenarioDrone d) => _service.SaveScenarioDrone(scenarioId, d);
        public ScenarioDrone AddScenarioDrone(string scenarioId, ScenarioDrone d) => _service.AddScenarioDrone(scenarioId, d);
        public void UpdateScenarioDrone(ScenarioDrone d) => _service.UpdateScenarioDrone(d);
        public void DeleteScenarioDrone(string id) => _service.DeleteScenarioDrone(id);
        public List<ScenarioDrone> GetScenarioDrones(string scenarioId) => _service.GetScenarioDrones(scenarioId);

        public void SaveDeployment(string scenarioId, List<ScenarioUnit> e) => _service.SaveDeployment(scenarioId, e);
        public ScenarioUnit AddDeploymentUnit(string scenarioId, ScenarioUnit u) => _service.AddDeploymentUnit(scenarioId, u);
        public void UpdateDeploymentUnit(ScenarioUnit u) => _service.UpdateDeploymentUnit(u);
        public void DeleteDeploymentUnit(string id) => _service.DeleteDeploymentUnit(id);
        public List<ScenarioUnit> GetDeploymentUnits(string scenarioId) => _service.GetDeploymentUnits(scenarioId);

        public void AddDetection(string scenarioId, ScenarioUnit d) => _service.AddDetection(scenarioId, d);
        public void DeleteDetection(string id) => _service.DeleteDetection(id);
        public List<ScenarioUnit> GetDetections(string scenarioId) => _service.GetDetections(scenarioId);

        public void SaveCloud(string scenarioId, CloudDispersal c) => _service.SaveCloudDispersal(scenarioId, c);
        public CloudDispersal GetCloud(string scenarioId) => _service.GetCloudDispersal(scenarioId);
        public void DeleteCloud(string scenarioId) => _service.DeleteCloudDispersal(scenarioId);

        public void SaveRoute(string scenarioId, string waveId, RoutePlan r, List<Waypoint> w) => _service.SaveRoute(scenarioId, waveId, r, w);
        public List<RoutePlan> GetRoutes(string scenarioId) => _service.GetRoutes(scenarioId);
        public void DeleteRoute(string id) => _service.DeleteRoute(id);
        public List<Waypoint> GetWaypoints(string scenarioId) => _service.GetWaypoints(scenarioId);
        public List<Waypoint> GetWaypointsByWave(string scenarioId, string waveId) => _service.GetWaypointsByWave(scenarioId, waveId);
        public void DeleteWaypoint(string id) => _service.DeleteWaypoint(id);

        public void UpdateStep(string scenarioId, int step) => _service.UpdateStep(scenarioId, step);

        public EnumMetadata GetEnums() => _service.GetEnums();

        [ContextMenu("Verify")]
        void Verify()
        {
            Awake();
            var scenario = CreateScenario("验证任务", "");
            Debug.Log($"ScenarioManager OK. Created: {scenario.Name} ({scenario.ScenarioNumber})");
        }
    }
}
