using System;
using System.IO;

namespace TeslaConsole.DiffTests
{
    /// <summary>
    /// Locates the two assemblies under comparison:
    ///   * Original  - original/TeslaConsole.exe  (the lost-source reference baseline)
    ///   * Recovered - bin/Release/net48/TeslaConsole.exe  (freshly built reconstruction)
    /// </summary>
    public static class AssemblyPaths
    {
        public static string RepoRoot { get; } = FindRepoRoot();

        public static string OriginalExe { get; } =
            Path.Combine(RepoRoot, "original", "TeslaConsole.exe");

        // The reconstruction's build output. Release is what README documents; fall
        // back to Debug so the suite still runs from either configuration.
        public static string RecoveredExe { get; } = FindRecoveredExe();

        // The product catalog copied next to the recovered exe.
        public static string RecoveredCatalog { get; } =
            Path.Combine(Path.GetDirectoryName(RecoveredExe), "RedPlanet", "Apps.xml");

        private static string FindRepoRoot()
        {
            var dir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
            while (dir != null)
            {
                if (File.Exists(Path.Combine(dir.FullName, "TeslaConsole.csproj")))
                    return dir.FullName;
                dir = dir.Parent;
            }
            throw new InvalidOperationException(
                "Could not locate repo root (TeslaConsole.csproj) above " +
                AppDomain.CurrentDomain.BaseDirectory);
        }

        private static string FindRecoveredExe()
        {
            string release = Path.Combine(RepoRoot, "bin", "Release", "net48", "TeslaConsole.exe");
            string debug = Path.Combine(RepoRoot, "bin", "Debug", "net48", "TeslaConsole.exe");

            // Test whichever build is freshest, so a stale config never silently wins.
            string best = null;
            DateTime bestTime = DateTime.MinValue;
            foreach (var candidate in new[] { release, debug })
            {
                if (!File.Exists(candidate)) continue;
                var t = File.GetLastWriteTimeUtc(candidate);
                if (t >= bestTime) { bestTime = t; best = candidate; }
            }
            // Fall back to the Release path; callers assert existence with a clear message.
            return best ?? release;
        }
    }
}
