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

namespace CounterDrone.Unity
{
    /// <summary>回放控制器 — 从帧数据库读取历史仿真数据</summary>
    public class ReplayController : MonoBehaviour
    {
        private FrameDataStore _frameStore;
        private IPathProvider _paths;

        public List<SimFrameRecord> CurrentFrames { get; private set; } = new();
        public int CurrentFrameIndex { get; private set; }
        public int TotalFrames { get; private set; }

        public void Awake()
        {
            _paths = new UnityPathProvider();
            _frameStore = new FrameDataStore(_paths);
        }

        public void LoadReplay(string taskId)
        {
            var db = _frameStore.CreateOrOpen(taskId);
            CurrentFrames = db.Table<SimFrameRecord>()
                .Where(f => f.TaskId == taskId)
                .OrderBy(f => f.FrameIndex)
                .ToList();
            db.Close();

            TotalFrames = CurrentFrames.Count > 0
                ? CurrentFrames.Max(f => f.FrameIndex) + 1
                : 0;
            CurrentFrameIndex = 0;

            Debug.Log($"Replay loaded: {CurrentFrames.Count} records, {TotalFrames} frames");
        }

        /// <summary>获取指定帧的所有实体快照</summary>
        public List<SimFrameRecord> GetFrame(int frameIndex)
        {
            return CurrentFrames.Where(f => f.FrameIndex == frameIndex).ToList();
        }

        [ContextMenu("Verify")]
        void Verify()
        {
            Awake();
            var framesDir = _paths.GetFramesDir();
            var files = System.IO.Directory.GetFiles(framesDir, "*.db");
            Debug.Log($"ReplayController OK. Frames dir: {framesDir}, files: {files.Length}");
        }
    }
}
