namespace MBN_STOCK_WEBVIEW.LegacyWeb.Tests;

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

    [Fact]
    public void Dedicated_profile_reuses_exact_debug_package_and_dryrun_guards()
    {
        Assert.Contains("-BuildFlavor DebugAppX", Wrapper, StringComparison.Ordinal);
        Assert.Contains("-DefinitionsOnly", Wrapper, StringComparison.Ordinal);
        Assert.Contains("[string]$LegacyDataDirectory", Wrapper, StringComparison.Ordinal);
        Assert.Contains(
            "'..\\MBN_STOCK_N\\MBN_STOCK_N\\bin\\Debug\\Data'",
            Wrapper,
            StringComparison.Ordinal);
        Assert.DoesNotMatch(@"(?i)C:\\Users\\[^\\]+", Wrapper);
        Assert.Contains("Assert-LocalConfigurationIsDryRun", Wrapper, StringComparison.Ordinal);
        Assert.Contains("Assert-NoTornadoConnection", Wrapper, StringComparison.Ordinal);
        Assert.Contains("Get-ExactDevelopmentPackage", Wrapper, StringComparison.Ordinal);
        Assert.Contains("[switch]$DefinitionsOnly", Shared, StringComparison.Ordinal);
        Assert.Contains("if ($DefinitionsOnly)", Shared, StringComparison.Ordinal);
        Assert.Contains("function Read-LocalHarnessEvidenceFile", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("$item.Length -gt 128KB", Wrapper, StringComparison.Ordinal);
        Assert.DoesNotContain(
            "Read-SmallJsonEvidenceFile $EvidencePath 'Local-state harness evidence'",
            Wrapper,
            StringComparison.Ordinal);
    }

    [Fact]
    public void Folder_pickers_are_real_click_owned_unique_and_escape_cancel_only()
    {
        Assert.Contains("SendApplicationClick(", Shared, StringComparison.Ordinal);
        Assert.Contains("SendEscapeToForegroundWindow", Shared, StringComparison.Ordinal);
        Assert.Contains("Key-up only releases the", Shared,
            StringComparison.Ordinal);
        Assert.Contains("caller separately proves that this exact", Shared,
            StringComparison.Ordinal);
        Assert.DoesNotContain("lost foreground before Escape was released", Shared,
            StringComparison.Ordinal);
        Assert.Contains("Wait-UniqueOwnedFolderPicker", Wrapper, StringComparison.Ordinal);
        Assert.Contains("OwnerChainContains", Wrapper, StringComparison.Ordinal);
        Assert.Contains("VisibleTopLevelWindows", Wrapper, StringComparison.Ordinal);
        Assert.Contains("EnumWindows(callback, IntPtr.Zero)", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("AutomationElement]::FromHandle($handle)", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("$windowClass -cne '#32770'", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("$revalidated[0].Handle -ne $picker.Handle", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("ControlType]::Button", Wrapper, StringComparison.Ordinal);
        Assert.Contains("Current.ClassName -ceq 'Button'", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("$automationId -ceq '1'", Wrapper, StringComparison.Ordinal);
        Assert.Contains("$automationId -ceq '2'", Wrapper, StringComparison.Ordinal);
        Assert.Contains("WindowPattern]::Pattern", Wrapper, StringComparison.Ordinal);
        Assert.Contains("$windowPattern.Current.IsModal", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("AcquireOwnedForeground", Wrapper, StringComparison.Ordinal);
        Assert.Contains("OwnerChainContains(window, expectedOwner)", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("uniqueNewPicker = $true", Wrapper, StringComparison.Ordinal);
        Assert.Contains("closedAfterEscape = $true", Wrapper, StringComparison.Ordinal);
        Assert.Contains("not destroyed after the one Escape input", Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("waitForTrustedPointerClick", Harness, StringComparison.Ordinal);
        Assert.Contains("isTrusted: event.isTrusted === true", Harness,
            StringComparison.Ordinal);
        Assert.Contains("settings file changed during a cancel-only smoke", Wrapper,
            StringComparison.Ordinal);
        Assert.DoesNotContain("reset-operator-folder", Harness, StringComparison.Ordinal);
    }

    [Fact]
    public void Comparison_import_requires_exact_source_known_baseline_and_idempotence()
    {
        Assert.Contains(
            "1EE76BC464FB1C44C8B6546E99CDC21C726C0E2C24AD344F5C19AE41BFC0D2F2",
            Wrapper,
            StringComparison.Ordinal);
        Assert.Contains(
            "13C07BA64587549EDA9C1A694F3DFA19875CB1F888F02C9E071F17C47739E087",
            Wrapper,
            StringComparison.Ordinal);
        Assert.Contains(
            "2575C2420800670B0022EBEE819BA3D9640DB14E9552426DF46075D079F1F697",
            Wrapper,
            StringComparison.Ordinal);
        Assert.Contains("baselineMode === \"fresh\" ? 8 : 0", Harness,
            StringComparison.Ordinal);
        Assert.Contains("baselineMode === \"fresh\" ? 0 : 8", Harness,
            StringComparison.Ordinal);
        Assert.Contains("receipt?.addedPairCount === expectedFirstAdded", Harness,
            StringComparison.Ordinal);
        Assert.Contains("receipt?.skippedDuplicateCount === expectedFirstSkipped", Harness,
            StringComparison.Ordinal);
        Assert.Contains("receipt?.addedPairCount === 0", Harness, StringComparison.Ordinal);
        Assert.Contains("receipt?.skippedDuplicateCount === 8", Harness,
            StringComparison.Ordinal);
        Assert.Contains(
            "initialDestinationMode = isFresh ? \"fresh\" : \"alreadyImported\"",
            Harness,
            StringComparison.Ordinal);
        Assert.Contains("$script:DestinationBaselineMode = if ($isFresh)", Wrapper,
            StringComparison.Ordinal);
        Assert.Equal(
            2,
            CountOccurrences(
                Harness,
                "allowBusy: true, allowDialog: true, timeoutMilliseconds: 90_000"));
        Assert.Contains("secondImportIdempotent = true", Harness, StringComparison.Ordinal);
        Assert.Contains("rowId: pair.rowId", Harness, StringComparison.Ordinal);
        Assert.Contains("displayLabel: pair.displayLabel", Harness, StringComparison.Ordinal);
        Assert.Contains(
            "initialPair.displayLabel !== \"KRX100지수 ↔ 코스피 지수\"",
            Harness,
            StringComparison.Ordinal);
        Assert.DoesNotContain("pair.first?.displayName", Harness, StringComparison.Ordinal);
        Assert.DoesNotContain("pair.second?.displayName", Harness, StringComparison.Ordinal);
        Assert.Contains("no input was retried", Harness, StringComparison.Ordinal);
    }

    [Fact]
    public void Harness_has_no_cdp_input_or_app_close_call_site()
    {
        Assert.Contains("\"Input.dispatchMouseEvent\"", Harness, StringComparison.Ordinal);
        Assert.DoesNotContain("rpc(\"Input.dispatchMouseEvent\"", Harness,
            StringComparison.Ordinal);
        Assert.DoesNotContain("rpc(\"Input.dispatchKeyEvent\"", Harness,
            StringComparison.Ordinal);
        Assert.DoesNotContain("rpc(\"Browser.close\"", Harness, StringComparison.Ordinal);
        Assert.DoesNotContain("rpc(\"Page.close\"", Harness, StringComparison.Ordinal);
        Assert.DoesNotContain("Stop-Process", Wrapper, StringComparison.OrdinalIgnoreCase);
        Assert.DoesNotContain("taskkill", Wrapper, StringComparison.OrdinalIgnoreCase);
    }

    [Fact]
    public void Initial_state_race_is_input_free_and_stdin_does_not_hold_node_open()
    {
        Assert.Contains("process.stdin.unref", Harness, StringComparison.Ordinal);
        Assert.Contains("label !== \"DryRun IDLE preflight\"", Harness,
            StringComparison.Ordinal);
        Assert.Contains("Only the input-free initial preflight", Harness,
            StringComparison.Ordinal);
        Assert.Contains("allowMissingState: true", Harness, StringComparison.Ordinal);
        Assert.Contains("last.safety.blockedOutboundMessages.length", Harness,
            StringComparison.Ordinal);
        Assert.Contains("last.dom.connectionText !== \"DRY RUN\"", Harness,
            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.");
    }
}
