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);
        }

        /// <summary>加载回放数据：优先使用传入的 frameStore 内存数据（仿真刚结束），否则读数据库</summary>
        public void LoadReplay(string scenarioId, FrameDataStore frameStore = null)
        {
            if (frameStore != null && frameStore.LiveFrames.Count > 0)
            {
                _frameStore = frameStore;
                CurrentFrames = _frameStore.LiveFrames;
            }
            else
            {
                _frameStore ??= new FrameDataStore(_paths);
                CurrentFrames = _frameStore.ReadFrames(scenarioId, 0, int.MaxValue);
            }

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

        /// <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}");
        }
    }
}
