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;

        public IScenarioService Service => _service;

        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 SimTaskRepository(_db), new CombatSceneRepository(_db),
                    new ControlZoneRepository(_db), new TargetConfigRepository(_db),
                    new EquipmentDeploymentRepository(_db), new CloudDispersalRepository(_db),
                    new RoutePlanRepository(_db), new WaypointRepository(_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 SimTask CreateTask(string name, string number) => _service.CreateTask(name, number);
        public void DeleteTask(string id) => _service.DeleteTask(id);
        public TaskFullConfig GetDetail(string id) => _service.GetTaskDetail(id);
        public PagedResult<SimTask> Search(string kw, string from, string to, int page, int size)
            => _service.SearchTasks(kw, from, to, page, size);

        public void SaveScene(string taskId, CombatScene s) => _service.SaveScene(taskId, s);
        public void SaveTarget(string taskId, TargetConfig t) => _service.SaveTarget(taskId, t);
        public void SaveDeployment(string taskId, List<EquipmentDeployment> e) => _service.SaveDeployment(taskId, e);
        public void SaveCloud(string taskId, CloudDispersal c) => _service.SaveCloudDispersal(taskId, c);
        public void SaveRoute(string taskId, string groupId, RoutePlan r, List<Waypoint> w) => _service.SaveRoute(taskId, groupId, r, w);
        public void UpdateStep(string taskId, int step) => _service.UpdateStep(taskId, step);

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