using System;
using System.IO;
using System.Reflection;

namespace CounterDrone.Core
{
    /// <summary>IPathProvider 的实现，用于单元测试环境</summary>
    public class TestPathProvider : IPathProvider
    {
        private readonly string _root;

        public TestPathProvider(string rootDir)
        {
            _root = rootDir;
            Directory.CreateDirectory(_root);
            CopyDataFiles();
        }

        /// <summary>从项目 data/ 目录复制 defaults.json 和 planner_config.json 到测试根目录</summary>
        private void CopyDataFiles()
        {
            var sourceDir = FindProjectDataDirectory();
            if (sourceDir == null) return;
            foreach (var file in new[] { "defaults.json", "planner_config.json" })
            {
                var src = Path.Combine(sourceDir, file);
                var dst = Path.Combine(_root, file);
                if (File.Exists(src))
                    File.Copy(src, dst, true); // 始终覆盖，确保测试用最新配置
            }
        }

        public static string? FindProjectDataDirectory()
        {
            var asmDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            if (asmDir == null) return null;
            // 从 bin/Debug/netX.X 往上走到仓库根
            var dir = asmDir;
            for (int i = 0; i < 10; i++)
            {
                var candidate = Path.Combine(dir, "data/defaults.json");
                if (File.Exists(candidate)) return Path.Combine(dir, "data");
                dir = Path.GetDirectoryName(dir);
                if (dir == null) break;
            }
            return null;
        }

        public string GetDataRoot() => _root;

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

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

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