using System;
using System.Collections.Generic;
using System.IO;
using CounterDrone.Core.Models;
using SQLite;

namespace CounterDrone.Core.Simulation
{
    public class FrameDataStore
    {
        private readonly IPathProvider _paths;
        /// <summary>帧数据保留天数，默认 180 天（6 个月）</summary>
        public int RetentionDays { get; set; } = 180;

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

        public SQLiteConnection CreateOrOpen(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;
        }

        public void WriteFrame(SQLiteConnection db, string taskId, int frameIdx, float timestamp, List<EntitySnapshot> snapshots)
        {
            foreach (var s in snapshots)
            {
                db.Insert(new SimFrameRecord
                {
                    TaskId = taskId,
                    FrameIndex = frameIdx,
                    Timestamp = timestamp,
                    EntityId = s.EntityId,
                    EntityType = (int)s.EntityType,
                    PosX = s.PosX,
                    PosY = s.PosY,
                    PosZ = s.PosZ,
                    RotX = s.RotX,
                    RotY = s.RotY,
                    RotZ = s.RotZ,
                    StateData = s.StateData,
                });
            }
        }

        public List<SimFrameRecord> ReadFrames(SQLiteConnection db, string taskId, int fromFrame, int toFrame)
        {
            return db.Table<SimFrameRecord>()
                     .Where(f => f.TaskId == taskId && f.FrameIndex >= fromFrame && f.FrameIndex <= toFrame)
                     .OrderBy(f => f.FrameIndex)
                     .ToList();
        }

        public void DeleteFrameDb(string taskId)
        {
            var dbPath = Path.Combine(_paths.GetFramesDir(), $"{taskId}.db");
            if (File.Exists(dbPath)) File.Delete(dbPath);
        }

        /// <summary>清理过期的帧数据库文件</summary>
        /// <returns>被删除的文件数量</returns>
        public int CleanupExpired()
        {
            var dir = _paths.GetFramesDir();
            if (!Directory.Exists(dir)) return 0;

            var cutoff = DateTime.Now.AddDays(-RetentionDays);
            var deleted = 0;

            foreach (var file in Directory.GetFiles(dir, "*.db"))
            {
                var creationTime = File.GetCreationTime(file);
                if (creationTime < cutoff)
                {
                    File.Delete(file);
                    deleted++;
                }
            }

            return deleted;
        }
    }
}
