using System;
using System.IO;
using CounterDrone.Core;
using CounterDrone.Core.Simulation;
using Xunit;

namespace CounterDrone.Core.Tests
{
    public class FrameDataStoreTests : IDisposable
    {
        private readonly string _testDir;
        private readonly FrameDataStore _store;

        public FrameDataStoreTests()
        {
            _testDir = Path.Combine(Path.GetTempPath(), $"cd_frames_{Guid.NewGuid():N}");
            var paths = new TestPathProvider(_testDir);
            _store = new FrameDataStore(paths);
        }

        public void Dispose()
        {
            if (Directory.Exists(_testDir)) Directory.Delete(_testDir, true);
        }

        [Fact]
        public void CleanupExpired_DeletesOldFiles()
        {
            // 设置为 0 天保留，所有文件都是"过期"的
            _store.RetentionDays = 0;

            // 创建一些假帧数据库
            var db1 = _store.CreateOrOpen("task_old_1");
            db1.Close();
            var db2 = _store.CreateOrOpen("task_old_2");
            db2.Close();

            var deleted = _store.CleanupExpired();
            Assert.Equal(2, deleted);

            // 文件应该被删除
            Assert.False(File.Exists(Path.Combine(_testDir, "frames", "task_old_1.db")));
            Assert.False(File.Exists(Path.Combine(_testDir, "frames", "task_old_2.db")));
        }

        [Fact]
        public void CleanupExpired_KeepsRecentFiles()
        {
            _store.RetentionDays = 365; // 保留 1 年

            var db = _store.CreateOrOpen("task_new");
            db.Close();

            // 手动修改创建时间为"最近"
            var filePath = Path.Combine(_testDir, "frames", "task_new.db");
            File.SetCreationTime(filePath, DateTime.Now);

            var deleted = _store.CleanupExpired();
            Assert.Equal(0, deleted);

            // 文件应该保留
            Assert.True(File.Exists(filePath));
        }

        [Fact]
        public void CleanupExpired_EmptyDir_ReturnsZero()
        {
            var deleted = _store.CleanupExpired();
            Assert.Equal(0, deleted);
        }

        [Fact]
        public void ReadFrames_ReturnsCorrectRange()
        {
            var db = _store.CreateOrOpen("task_read");
            var snapshots = new System.Collections.Generic.List<EntitySnapshot>
            {
                new EntitySnapshot { EntityId = "d1", EntityType = Models.EntityType.Drone, PosX = 100 },
            };

            _store.WriteFrame(db, "task_read", 0, 0f, snapshots);
            _store.WriteFrame(db, "task_read", 1, 0.05f, snapshots);
            _store.WriteFrame(db, "task_read", 2, 0.10f, snapshots);

            var frames = _store.ReadFrames(db, "task_read", 1, 2);
            Assert.Equal(2, frames.Count);
            Assert.Equal(1, frames[0].FrameIndex);
            Assert.Equal(2, frames[1].FrameIndex);

            db.Close();
        }
    }
}
