using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;

internal static class Program
{
    private static Type SettingsType = null!;
    private static ConstructorInfo ServiceConstructor = null!;
    private static MethodInfo SaveMethod = null!;
    private static PropertyInfo CommitHook = null!;
    private static readonly JsonSerializerOptions IndentedJson = new() { WriteIndented = true };
    private static readonly List<string> Cases = [];

    private static int Main(string[] args)
    {
        if (args.Length != 3) throw new ArgumentException("Expected: <assembly> <isolated-root> <result-json>.");
        var assemblyPath = Path.GetFullPath(args[0]);
        var root = Path.GetFullPath(args[1]);
        var resultPath = Path.GetFullPath(args[2]);
        if (!File.Exists(assemblyPath)) throw new FileNotFoundException("Product assembly not found.", assemblyPath);
        if (Directory.Exists(root) && Directory.EnumerateFileSystemEntries(root).Any())
            throw new IOException($"The isolated test root must start empty: {root}");
        Directory.CreateDirectory(root);

        var assembly = Assembly.LoadFrom(assemblyPath);
        SettingsType = assembly.GetType("FreeVideoConverter.Services.AppSettings", throwOnError: true)!;
        var serviceType = assembly.GetType("FreeVideoConverter.Services.AppSettingsService", throwOnError: true)!;
        ServiceConstructor = serviceType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null,
            [typeof(string)], null) ?? throw new MissingMethodException(serviceType.FullName, ".ctor(string)");
        SaveMethod = serviceType.GetMethod("Save", BindingFlags.Instance | BindingFlags.Public)
            ?? throw new MissingMethodException(serviceType.FullName, "Save");
        CommitHook = serviceType.GetProperty("BeforeSettingsCommitForTests", BindingFlags.Static | BindingFlags.NonPublic)
            ?? throw new MissingMemberException(serviceType.FullName, "BeforeSettingsCommitForTests");

        try
        {
            TestNoChangeIsObservablyReadOnly(Path.Combine(root, "no-change"));
            TestChangedSaveIsAtomic(Path.Combine(root, "changed"));
            TestInjectedFailureRollsBack(Path.Combine(root, "injected-failure"));
            TestLockedTargetIsUntouched(Path.Combine(root, "locked"));
            TestConcurrentWritersDoNotPartiallyCommit(Path.Combine(root, "concurrent"));
            TestConcurrentMutationIsDetected(Path.Combine(root, "mutation"));
            TestCorruptInputAndFailureHaveNoPartial(Path.Combine(root, "corrupt"));
            TestHardLinkIsRejected(Path.Combine(root, "hard-link"));
            TestReparseParentIsRejected(Path.Combine(root, "reparse"));
        }
        finally { SetHook(null); }

        var result = new
        {
            Schema = "free-video-converter.app-settings-focused/v1",
            Success = true,
            Assembly = assemblyPath,
            AssemblySha256 = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(assemblyPath))),
            Root = root,
            Cases
        };
        var json = JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true });
        using (var stream = new FileStream(resultPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough))
        {
            var bytes = new UTF8Encoding(false).GetBytes(json + Environment.NewLine);
            stream.Write(bytes);
            stream.Flush(flushToDisk: true);
        }
        Console.WriteLine(json);
        return 0;
    }

    private static void TestNoChangeIsObservablyReadOnly(string directory)
    {
        Directory.CreateDirectory(directory);
        var path = Path.Combine(directory, "settings.json");
        var service = NewService(path);
        var settings = NewSettings("same");
        Save(service, settings);

        var creation = new DateTime(2020, 1, 2, 3, 4, 6, DateTimeKind.Utc);
        var write = new DateTime(2020, 2, 3, 4, 5, 6, DateTimeKind.Utc);
        var parentWrite = new DateTime(2020, 3, 4, 5, 6, 8, DateTimeKind.Utc);
        File.SetAttributes(path, FileAttributes.Archive | FileAttributes.ReadOnly);
        File.SetCreationTimeUtc(path, creation);
        File.SetLastWriteTimeUtc(path, write);
        Directory.SetLastWriteTimeUtc(directory, parentWrite);
        var before = Capture(path);
        Thread.Sleep(1100);
        Save(service, settings);
        var after = Capture(path);
        AssertSnapshotsEqual(before, after, "Exact no-change save rewrote filesystem metadata.");

        File.SetAttributes(path, FileAttributes.Normal);
        var compact = JsonSerializer.SerializeToUtf8Bytes(settings, SettingsType, new JsonSerializerOptions { WriteIndented = false });
        File.WriteAllBytes(path, compact);
        File.SetAttributes(path, FileAttributes.Archive | FileAttributes.ReadOnly);
        File.SetCreationTimeUtc(path, creation);
        File.SetLastWriteTimeUtc(path, write);
        Directory.SetLastWriteTimeUtc(directory, parentWrite);
        before = Capture(path);
        Thread.Sleep(1100);
        Save(service, settings);
        after = Capture(path);
        AssertSnapshotsEqual(before, after, "Semantically identical no-change save rewrote filesystem metadata.");
        AssertNoResidue(directory);
        Cases.Add("identical bytes and equivalent JSON preserve bytes/length/creation/mtime/attributes/parent mtime");
    }

    private static void TestChangedSaveIsAtomic(string directory)
    {
        Directory.CreateDirectory(directory);
        var path = Path.Combine(directory, "settings.json");
        var service = NewService(path);
        var oldSettings = NewSettings("old");
        var newSettings = NewSettings("new");
        Save(service, oldSettings);
        var oldBytes = File.ReadAllBytes(path);
        var expected = CanonicalBytes(newSettings);
        var entered = new ManualResetEventSlim(false);
        var release = new ManualResetEventSlim(false);
        Exception? hookFailure = null;
        string? stagingPath = null;
        SetHook(candidate =>
        {
            try
            {
                stagingPath = candidate;
                Assert(Path.GetDirectoryName(candidate)!.Equals(directory, StringComparison.OrdinalIgnoreCase), "Staging escaped the settings directory.");
                Assert(File.ReadAllBytes(candidate).AsSpan().SequenceEqual(expected), "Staging did not contain the complete new payload.");
                Assert(File.ReadAllBytes(path).AsSpan().SequenceEqual(oldBytes), "Target changed before atomic commit.");
            }
            catch (Exception ex) { hookFailure = ex; }
            finally { entered.Set(); }
            if (!release.Wait(TimeSpan.FromSeconds(10))) throw new TimeoutException("Atomic-save test was not released.");
        });

        var task = Task.Run(() => Save(service, newSettings));
        Assert(entered.Wait(TimeSpan.FromSeconds(10)), "Atomic-save hook was not reached.");
        Assert(File.ReadAllBytes(path).AsSpan().SequenceEqual(oldBytes), "Target changed while staging was blocked.");
        Assert(stagingPath is not null && File.Exists(stagingPath), "Unique staging file was not observable before commit.");
        release.Set();
        task.GetAwaiter().GetResult();
        SetHook(null);
        if (hookFailure is not null) throw hookFailure;
        Assert(File.ReadAllBytes(path).AsSpan().SequenceEqual(expected), "Atomic commit did not install the complete new payload.");
        AssertNoResidue(directory);
        Cases.Add("changed payload stages completely in the same directory before atomic commit");
    }

    private static void TestInjectedFailureRollsBack(string directory)
    {
        Directory.CreateDirectory(directory);
        var path = Path.Combine(directory, "settings.json");
        var service = NewService(path);
        Save(service, NewSettings("baseline"));
        var before = Capture(path);
        SetHook(_ => throw new InvalidOperationException("focused injected failure"));
        AssertThrows<InvalidOperationException>(() => Save(service, NewSettings("must-not-commit")));
        SetHook(null);
        var after = Capture(path);
        Assert(before.Bytes.AsSpan().SequenceEqual(after.Bytes), "Injected failure changed target bytes.");
        Assert(before.Length == after.Length && before.CreationUtcTicks == after.CreationUtcTicks &&
               before.LastWriteUtcTicks == after.LastWriteUtcTicks && before.Attributes == after.Attributes,
            "Injected failure changed target metadata.");
        AssertNoResidue(directory);
        Cases.Add("pre-commit exception preserves the complete old target and leaves no staging residue");
    }

    private static void TestLockedTargetIsUntouched(string directory)
    {
        Directory.CreateDirectory(directory);
        var path = Path.Combine(directory, "settings.json");
        var service = NewService(path);
        Save(service, NewSettings("locked-old"));
        var before = Capture(path);
        using (var locked = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None))
            AssertThrows<IOException>(() => Save(service, NewSettings("locked-new")));
        var after = Capture(path);
        AssertSnapshotsEqualExceptParent(before, after, "Locked-target failure changed the target.");
        AssertNoResidue(directory);
        Cases.Add("exclusive target lock fails closed before staging and preserves the target");
    }

    private static void TestConcurrentWritersDoNotPartiallyCommit(string directory)
    {
        Directory.CreateDirectory(directory);
        var path = Path.Combine(directory, "settings.json");
        var firstService = NewService(path);
        var secondService = NewService(path);
        Save(firstService, NewSettings("concurrent-base"));
        var firstSettings = NewSettings("concurrent-first");
        var secondSettings = NewSettings("concurrent-second");
        var firstBytes = CanonicalBytes(firstSettings);
        var entered = new ManualResetEventSlim(false);
        var release = new ManualResetEventSlim(false);
        SetHook(_ =>
        {
            entered.Set();
            if (!release.Wait(TimeSpan.FromSeconds(10))) throw new TimeoutException("Concurrent writer test was not released.");
        });
        var first = Task.Run(() => Save(firstService, firstSettings));
        Assert(entered.Wait(TimeSpan.FromSeconds(10)), "First concurrent writer did not reach commit hook.");
        var secondError = CaptureException(() => Save(secondService, secondSettings));
        Assert(secondError is IOException, "Second concurrent writer did not fail closed on the same-directory gate.");
        release.Set();
        first.GetAwaiter().GetResult();
        SetHook(null);
        Assert(File.ReadAllBytes(path).AsSpan().SequenceEqual(firstBytes), "Concurrent save produced a mixed or unexpected target.");
        AssertNoResidue(directory);
        Cases.Add("concurrent writers serialize through CreateNew gate; loser fails and winner commits one whole payload");
    }

    private static void TestConcurrentMutationIsDetected(string directory)
    {
        Directory.CreateDirectory(directory);
        var path = Path.Combine(directory, "settings.json");
        var service = NewService(path);
        Save(service, NewSettings("mutation-base"));
        var outsider = Encoding.UTF8.GetBytes("{\"Language\":\"external\"}");
        SetHook(_ => File.WriteAllBytes(path, outsider));
        AssertThrows<IOException>(() => Save(service, NewSettings("mutation-pending")));
        SetHook(null);
        Assert(File.ReadAllBytes(path).AsSpan().SequenceEqual(outsider), "Concurrent external mutation was overwritten.");
        AssertNoResidue(directory);
        Cases.Add("target mutation between staging and commit is detected and never silently overwritten");
    }

    private static void TestCorruptInputAndFailureHaveNoPartial(string directory)
    {
        Directory.CreateDirectory(directory);
        var path = Path.Combine(directory, "settings.json");
        var corrupt = Encoding.UTF8.GetBytes("{ this is not valid json");
        File.WriteAllBytes(path, corrupt);
        var service = NewService(path);
        SetHook(_ => throw new InvalidOperationException("corrupt rollback"));
        AssertThrows<InvalidOperationException>(() => Save(service, NewSettings("repair")));
        SetHook(null);
        Assert(File.ReadAllBytes(path).AsSpan().SequenceEqual(corrupt), "Failed corrupt-file repair changed the original.");
        AssertNoResidue(directory);
        var repaired = NewSettings("repair");
        Save(service, repaired);
        Assert(File.ReadAllBytes(path).AsSpan().SequenceEqual(CanonicalBytes(repaired)), "Corrupt settings were not atomically replaced by a complete payload.");
        AssertNoResidue(directory);
        Cases.Add("corrupt input remains intact on failure and is wholly replaced on a successful repair");
    }

    private static void TestHardLinkIsRejected(string directory)
    {
        Directory.CreateDirectory(directory);
        var path = Path.Combine(directory, "settings.json");
        var alias = Path.Combine(directory, "settings-hardlink.json");
        var service = NewService(path);
        Save(service, NewSettings("hardlink-old"));
        CreateHardLink(alias, path);
        var before = File.ReadAllBytes(path);
        AssertThrows<IOException>(() => Save(NewService(alias), NewSettings("hardlink-new")));
        Assert(File.ReadAllBytes(path).AsSpan().SequenceEqual(before) && File.ReadAllBytes(alias).AsSpan().SequenceEqual(before),
            "Hard-link rejection changed an aliased entry.");
        File.Delete(alias);
        AssertNoResidue(directory);
        Cases.Add("multi-link settings targets are rejected before write");
    }

    private static void TestReparseParentIsRejected(string directory)
    {
        Directory.CreateDirectory(directory);
        var real = Path.Combine(directory, "real-parent");
        var alias = Path.Combine(directory, "alias-parent");
        Directory.CreateDirectory(real);
        var realPath = Path.Combine(real, "settings.json");
        var service = NewService(realPath);
        Save(service, NewSettings("reparse-old"));
        Directory.CreateSymbolicLink(alias, real);
        var before = File.ReadAllBytes(realPath);
        AssertThrows<IOException>(() => Save(NewService(Path.Combine(alias, "settings.json")), NewSettings("reparse-new")));
        Assert(File.ReadAllBytes(realPath).AsSpan().SequenceEqual(before), "Reparse-parent rejection changed the physical target.");
        Directory.Delete(alias);
        AssertNoResidue(real);
        Cases.Add("reparse parent is rejected before write and does not escape the isolated directory");
    }

    private static object NewSettings(string language)
    {
        var settings = Activator.CreateInstance(SettingsType) ?? throw new InvalidOperationException("Could not construct settings.");
        SettingsType.GetProperty("Language")!.SetValue(settings, language);
        SettingsType.GetProperty("OutputDirectory")!.SetValue(settings, Path.Combine(Path.GetTempPath(), "FvcFocusedOutput"));
        return settings;
    }

    private static object NewService(string path) => ServiceConstructor.Invoke([Path.GetFullPath(path)]);

    private static byte[] CanonicalBytes(object settings) =>
        JsonSerializer.SerializeToUtf8Bytes(settings, SettingsType, IndentedJson);

    private static void Save(object service, object settings)
    {
        try { SaveMethod.Invoke(service, [settings]); }
        catch (TargetInvocationException ex) when (ex.InnerException is not null)
        {
            ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
            throw;
        }
    }

    private static void SetHook(Action<string>? hook) => CommitHook.SetValue(null, hook);

    private static Exception? CaptureException(Action action)
    {
        try { action(); return null; }
        catch (Exception ex) { return ex; }
    }

    private static void AssertThrows<T>(Action action) where T : Exception
    {
        var error = CaptureException(action);
        if (error is not T) throw new InvalidOperationException($"Expected {typeof(T).Name}, received {error?.GetType().Name ?? "no exception"}.", error);
    }

    private static FileSnapshot Capture(string path)
    {
        var info = new FileInfo(path);
        info.Refresh();
        var directory = info.Directory ?? throw new InvalidOperationException("Settings file has no parent.");
        directory.Refresh();
        return new FileSnapshot(File.ReadAllBytes(path), info.Length, info.CreationTimeUtc.Ticks,
            info.LastWriteTimeUtc.Ticks, info.Attributes, directory.LastWriteTimeUtc.Ticks,
            Directory.EnumerateFileSystemEntries(directory.FullName).Select(Path.GetFileName).OrderBy(x => x, StringComparer.Ordinal).ToArray()!);
    }

    private static void AssertSnapshotsEqual(FileSnapshot expected, FileSnapshot actual, string message)
    {
        AssertSnapshotsEqualExceptParent(expected, actual, message);
        Assert(expected.ParentLastWriteUtcTicks == actual.ParentLastWriteUtcTicks, message + " Parent mtime differs.");
        Assert(expected.Entries.SequenceEqual(actual.Entries, StringComparer.Ordinal), message + " Directory entries differ.");
    }

    private static void AssertSnapshotsEqualExceptParent(FileSnapshot expected, FileSnapshot actual, string message) =>
        Assert(expected.Bytes.AsSpan().SequenceEqual(actual.Bytes) && expected.Length == actual.Length &&
               expected.CreationUtcTicks == actual.CreationUtcTicks && expected.LastWriteUtcTicks == actual.LastWriteUtcTicks &&
               expected.Attributes == actual.Attributes, message);

    private static void AssertNoResidue(string directory)
    {
        var residue = Directory.EnumerateFileSystemEntries(directory)
            .Where(path => Path.GetFileName(path).EndsWith(".write.lock", StringComparison.OrdinalIgnoreCase) ||
                           Path.GetFileName(path).EndsWith(".save.tmp", StringComparison.OrdinalIgnoreCase)).ToArray();
        Assert(residue.Length == 0, "Settings save left gate or staging residue: " + string.Join(", ", residue));
    }

    private static void Assert(bool condition, string message)
    {
        if (!condition) throw new InvalidOperationException(message);
    }

    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CreateHardLinkW")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CreateHardLinkNative(string fileName, string existingFileName, IntPtr securityAttributes);

    private static void CreateHardLink(string alias, string target)
    {
        if (!CreateHardLinkNative(alias, target, IntPtr.Zero))
            throw new IOException("Could not create focused hard-link fixture.", new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()));
    }

    private sealed record FileSnapshot(byte[] Bytes, long Length, long CreationUtcTicks, long LastWriteUtcTicks,
        FileAttributes Attributes, long ParentLastWriteUtcTicks, string[] Entries);
}
