namespace MBN_STOCK_WEBVIEW.LegacyWeb.Tests;

public sealed class LegacyPackageAppearanceSmokeContractTests
{
    private static readonly string Root = FindRepositoryRoot();
    private static readonly string Wrapper = Read(
        "scripts", "Invoke-LegacyPackageAppearanceSmoke.ps1");
    private static readonly string Harness = Read(
        "scripts", "Test-LegacyPackageAppearanceSmoke.mjs");

    [Fact]
    public void Dedicated_runner_reuses_exact_debug_package_dryrun_and_close_guards()
    {
        Assert.Contains("-BuildFlavor DebugAppX", Wrapper, StringComparison.Ordinal);
        Assert.Contains("-DefinitionsOnly", Wrapper, StringComparison.Ordinal);
        Assert.Contains("Get-ExactDevelopmentPackage", Wrapper, StringComparison.Ordinal);
        Assert.Contains("Assert-LocalConfigurationIsDryRun", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("Assert-NoTornadoConnection", Wrapper, StringComparison.Ordinal);
        Assert.Contains("Start-ExactAppearanceApplication $registration 1", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("Start-ExactAppearanceApplication $registration 2", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains(
            "Wait-StartupIntroDismissed $application $Registration.Executable",
            Wrapper,
            StringComparison.Ordinal);
        Assert.Equal(2, CountOccurrences(Wrapper, "Close-ExactAppearanceApplication $"));
        Assert.DoesNotContain("Stop-Process", Wrapper,
            StringComparison.OrdinalIgnoreCase);
        Assert.DoesNotContain("taskkill", Wrapper,
            StringComparison.OrdinalIgnoreCase);
        Assert.DoesNotMatch(@"(?i)C:\\Users\\[^\\]+", Wrapper);
    }

    [Fact]
    public void Three_selects_use_trusted_windows_mouse_and_keyboard_once_per_phase()
    {
        Assert.Contains("SendApplicationClick(", Wrapper, StringComparison.Ordinal);
        Assert.Contains("SendClosedSelectKeys(", Wrapper, StringComparison.Ordinal);
        Assert.Contains("[FieldOffset(0)] public MouseInput Mouse", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("[FieldOffset(0)] public KeyboardInput Keyboard", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("[FieldOffset(0)] public HardwareInput Hardware", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("IntPtr.Size == 8 ? 40 : 28", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("inputSize != ExpectedInputStructureBytes()", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("event.isTrusted === true", Harness, StringComparison.Ordinal);
        Assert.Contains("trustedChange: true", Harness, StringComparison.Ordinal);
        Assert.Contains("physicalKeyCounts:", Harness, StringComparison.Ordinal);
        Assert.Contains("home: ack.homeKeyCalls", Harness, StringComparison.Ordinal);
        Assert.Contains("arrowDown: ack.arrowDownKeyCalls", Harness,
            StringComparison.Ordinal);
        Assert.Contains("enter: ack.enterKeyCalls", Harness, StringComparison.Ordinal);
        Assert.Contains("A native HTML <select> popup consumes Home/ArrowDown/Enter", Harness,
            StringComparison.Ordinal);
        Assert.DoesNotContain("trustedKeyDowns.length >= expectedKeyCalls", Harness,
            StringComparison.Ordinal);
        Assert.DoesNotContain("trustedKeyDownCount -lt", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("selection.physicalKeyCounts.home -ne 1", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("selection.physicalKeyCounts.arrowDown -ne $expectedDownCount", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("selection.physicalKeyCounts.enter -ne 1", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("exchange.physicalInput.change.isTrusted -ne $true", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("exchange.physicalInput.change.value -cne", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("exchange.physicalKeyCounts.arrowDown -ne", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("nextExchangeSequence !== 5", Harness,
            StringComparison.Ordinal);
        Assert.Contains("evidence.exchanges.length !== 4", Harness,
            StringComparison.Ordinal);
        Assert.Contains(
            "[\"colorTheme\", \"viewMode\", \"startWorkspace\"]",
            Harness,
            StringComparison.Ordinal);
        Assert.Contains("inputRetryCount: 0", Harness, StringComparison.Ordinal);
        Assert.Contains("inputRetryCount = 0", Wrapper, StringComparison.Ordinal);
    }

    [Fact]
    public void Harness_has_no_synthetic_input_or_appearance_bridge_post()
    {
        foreach (var method in new[]
                 {
                     "Input.dispatchMouseEvent",
                     "Input.dispatchKeyEvent",
                     "Input.insertText"
                 })
        {
            Assert.Contains($"\"{method}\"", Harness, StringComparison.Ordinal);
            Assert.DoesNotContain($"rpc(\"{method}\"", Harness,
                StringComparison.Ordinal);
        }
        Assert.DoesNotMatch(
            @"postMessage\s*\(\s*\{\s*type:\s*['""]set-operator-appearance",
            Harness);
        Assert.DoesNotMatch(
            @"(?:\.value\s*=(?!=)|dispatchEvent\s*\(|\.click\s*\(|localStorage\.setItem)",
            Harness);
        Assert.Contains(
            "window.chrome.webview.postMessage({ type: \"ready\", payload: {} })",
            Harness,
            StringComparison.Ordinal);
        Assert.Contains("outbound.length !== 1", Harness, StringComparison.Ordinal);
    }

    [Fact]
    public void Relaunch_proves_persisted_start_behavior_before_any_settings_click()
    {
        Assert.Contains("persisted-appearance-after-relaunch", Harness,
            StringComparison.Ordinal);
        Assert.Contains("persisted start workspace behavior", Harness,
            StringComparison.Ordinal);
        Assert.Contains(
            "snapshot.dom.activeWorkspace === expectedStartupWorkspace",
            Harness,
            StringComparison.Ordinal);
        Assert.Contains("startWorkspaceBehaviorVerifiedBeforeInput = true", Harness,
            StringComparison.Ordinal);
        Assert.Contains("startWorkspaceBehaviorVerifiedBeforeInput -ne $true", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("persistenceVerifiedBeforeInput", Wrapper,
            StringComparison.Ordinal);
    }

    [Fact]
    public void Original_settings_have_exact_raw_recovery_for_present_and_absent_baselines()
    {
        Assert.Contains("Initialize-ExactBaselineRecovery", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("operatorSettingsOriginallyAbsent", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("Restore-ExactBaselineSettings", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("BaselineRestoreAttempted", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("restoration is one-shot and was already attempted", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("[IO.File]::Replace(", Wrapper, StringComparison.Ordinal);
        Assert.Contains("$replacementBackupPath", Wrapper, StringComparison.Ordinal);
        Assert.Contains("[IO.File]::Delete($replacementBackupPath)", Wrapper,
            StringComparison.Ordinal);
        Assert.DoesNotContain(
            "[IO.File]::Replace($temporaryPath, $OperatorSettingsPath, $null",
            Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("[IO.File]::Delete($OperatorSettingsPath)", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("exactOriginalBytesRestored = $true", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("recoveryCopyRemoved", Wrapper, StringComparison.Ordinal);
        Assert.Contains("The application was intentionally left open", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("no input retry, close retry,", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("one-shot settings restoration had an unclear or failed result", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("retried. Preserve the recovery evidence", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("[IO.Path]::GetFileNameWithoutExtension($Output)", Wrapper,
            StringComparison.Ordinal);
        Assert.DoesNotContain("[IO.Path]::ChangeExtension($Output, $null)", Wrapper,
            StringComparison.Ordinal);
    }

    [Fact]
    public void Evidence_is_bounded_create_new_and_hash_sealed()
    {
        Assert.Contains("flag: \"wx\"", Harness, StringComparison.Ordinal);
        Assert.Contains("$item.Length -gt 512KB", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("[IO.FileMode]::CreateNew", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("$stream.Flush($true)", Wrapper, StringComparison.Ordinal);
        Assert.Contains("phaseEvidenceSha256", Wrapper, StringComparison.Ordinal);
        Assert.Contains("screenshotSha256", Wrapper, StringComparison.Ordinal);
    }

    private static string Read(params string[] segments) =>
        File.ReadAllText(Path.Combine([Root, .. segments]));

    private static int CountOccurrences(string value, string token) =>
        value.Split(token, StringSplitOptions.None).Length - 1;

    private static string FindRepositoryRoot()
    {
        var current = new DirectoryInfo(AppContext.BaseDirectory);
        while (current is not null)
        {
            if (File.Exists(Path.Combine(current.FullName, "MBN_STOCK_WEBVIEW.sln")))
            {
                return current.FullName;
            }
            current = current.Parent;
        }
        throw new DirectoryNotFoundException("Repository root was not found.");
    }
}
