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

namespace CounterDrone.Unity
{
    public class ReportManager : MonoBehaviour
    {
        private IReportService _service;
        private IPathProvider _paths;
        private SQLite.SQLiteConnection _db;

        public IReportService Service => _service;

        public void Awake()
        {
            _paths = new UnityPathProvider();
            _db = new DatabaseManager(_paths).OpenMainDb();
            SqliteConnectionTracker.Track(_db);
            _service = new ReportService(_db, _paths);
        }

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

        public SimulationReport Generate(string scenarioId, ScenarioConfig cfg, List<SimEvent> events, string status, float duration)
            => _service.Generate(scenarioId, cfg, events, status, duration);

        public SimulationReport Get(string id) => _service.GetReport(id);
        public void Delete(string id) => _service.DeleteReport(id);
        public PagedResult<SimulationReport> Search(string kw, string from, string to, int page, int size)
            => _service.SearchReports(kw, from, to, page, size);

        /// <summary>导出报告为字节数组。format: "pdf" | "md"</summary>
        public byte[] ExportReport(string reportId, string format)
            => _service.ExportReport(reportId, format);

        /// <summary>导出报告到指定目录，返回文件路径。format: "pdf" | "md"</summary>
        public string Export(string reportId, string outputDir, string format)
            => _service.ExportToFile(reportId, outputDir, format);

        /// <summary>导出 Markdown 报告到默认报告目录，返回文件路径</summary>
        public string Export(string reportId)
            => Export(reportId, System.IO.Path.Combine(_paths.GetDataRoot(), "reports"), "md");

        [ContextMenu("Verify")]
        void Verify()
        {
            Awake();
            Debug.Log($"ReportManager OK. Reports dir: {System.IO.Path.Combine(_paths.GetDataRoot(), "reports")}");
        }
    }
}
