using System.IO;
using CounterDrone.Core;
using UnityEngine;

namespace CounterDrone.Unity
{
    public class UnityPathProvider : IPathProvider
    {
        private string _root;
        private bool _copied;

        public string GetDataRoot()
        {
            if (_root == null)
            {
                _root = Application.persistentDataPath;
                Directory.CreateDirectory(_root);
                CopyDataFiles();
            }
            return _root;
        }

        /// <summary>首次运行时从 StreamingAssets 复制默认数据文件到 persistentDataPath</summary>
        private void CopyDataFiles()
        {
            if (_copied) return;
            _copied = true;
            var sourceDir = Application.streamingAssetsPath;
            if (!Directory.Exists(sourceDir)) return;
            foreach (var file in new[] { "defaults.json", "planner_config.json" })
            {
                var dst = Path.Combine(_root, file);
                if (File.Exists(dst)) continue;
                var src = Path.Combine(sourceDir, file);
                if (File.Exists(src)) File.Copy(src, dst);
            }
        }

        public string GetMainDbPath() => Path.Combine(GetDataRoot(), "main.db");

        public string GetFramesDir()
        {
            var dir = Path.Combine(GetDataRoot(), "frames");
            Directory.CreateDirectory(dir);
            return dir;
        }

        public string GetModelsDir()
        {
            var dir = Path.Combine(GetDataRoot(), "models");
            Directory.CreateDirectory(dir);
            return dir;
        }
    }
}
