using System.Net;
using System.Security.Cryptography;
using MBN_STOCK_WEBVIEW.Core.Playout;
using MBN_STOCK_WEBVIEW.Playout.Configuration;
using MBN_STOCK_WEBVIEW.Playout.Interop;
using MBN_STOCK_WEBVIEW.Playout.Registration;
using MBN_STOCK_WEBVIEW.Playout.Runtime;
using MBN_STOCK_WEBVIEW.Playout.Safety;

namespace MBN_STOCK_WEBVIEW.Playout.Diagnostics;

internal sealed record PgmCutsSequenceRequest(
    string Host,
    int Port,
    string ExpectedPgmWindowTitle,
    string SceneRoot,
    int ObservationMilliseconds = PgmCutsSequenceRunner.RequiredObservationMilliseconds);

internal enum PgmCutsSequenceStage
{
    Connect,
    PrepareFirst,
    TakeIn,
    Next,
    TakeOut,
    Disconnect
}

internal enum PgmCutsObservationStage
{
    First,
    Next,
    TakeOut
}

internal sealed record PgmCutsSequenceCommandReport(
    PgmCutsSequenceStage Stage,
    PlayoutResultCode Code);

internal sealed record PgmCutsSequenceReport(
    bool RequestValidated,
    bool HashPinsPresent,
    bool TargetGatePassed,
    bool EngineCreated,
    bool RenderCommandAttempted,
    bool DisconnectAttempted,
    bool QuarantineAttempted,
    bool QuarantineCompleted,
    bool Completed,
    bool OutcomeUnknown,
    IReadOnlyList<PgmCutsSequenceCommandReport> Commands,
    string? ErrorCode);

internal interface IPgmCutsSequenceHashPinRequirement
{
    bool IsSatisfied();
}

internal interface IPgmCutsSequenceAssetLease : IDisposable;

internal interface IPgmCutsSequenceAssetLeaseFactory
{
    bool TryAcquire(
        PgmCutsSequencePlan plan,
        out IPgmCutsSequenceAssetLease? lease);
}

internal interface IPgmCutsSequenceDelay
{
    Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken);
}

internal interface IPgmCutsSequenceEngineFactory
{
    IPlayoutEngine Create(
        PgmCutsSequencePlan plan,
        PgmDiagnosticTargetSnapshot baseline);
}

internal sealed record PgmCutsSequencePlan(
    PgmConnectDiagnosticRequest DiagnosticRequest,
    IPAddress ParsedHost,
    ValidatedPlayoutOptions Options,
    PlayoutCue FirstCue,
    PlayoutCue NextCue,
    string FirstAssetPath,
    string NextAssetPath,
    TimeSpan ObservationDuration);

internal sealed class PgmCutsSequenceRunner
{
    internal const int RequiredObservationMilliseconds = 5_000;
    private const string FirstSceneCode = "5001";
    private const string NextSceneCode = "5006";

    private readonly IPgmDiagnosticSafetyProbe _safetyProbe;
    private readonly IPgmCutsSequenceHashPinRequirement _hashPins;
    private readonly IPgmCutsSequenceAssetLeaseFactory _assetLeases;
    private readonly IPgmCutsSequenceEngineFactory _engineFactory;
    private readonly IPgmCutsSequenceDelay _delay;

    internal PgmCutsSequenceRunner()
        : this(
            new WindowsPgmDiagnosticSafetyProbe(),
            new ProcessPgmCutsSequenceHashPinRequirement(),
            engineFactory: null,
            new SystemPgmCutsSequenceDelay(),
            new FixedPgmCutsSequenceAssetLeaseFactory())
    {
    }

    internal PgmCutsSequenceRunner(
        IPgmDiagnosticSafetyProbe safetyProbe,
        IPgmCutsSequenceHashPinRequirement hashPins,
        IPgmCutsSequenceEngineFactory? engineFactory,
        IPgmCutsSequenceDelay delay,
        IPgmCutsSequenceAssetLeaseFactory? assetLeases = null)
    {
        _safetyProbe = safetyProbe;
        _hashPins = hashPins;
        _assetLeases = assetLeases ?? new FixedPgmCutsSequenceAssetLeaseFactory();
        _engineFactory = engineFactory ?? new FullPgmCutsSequenceEngineFactory(safetyProbe);
        _delay = delay;
    }

    internal async Task<PgmCutsSequenceReport> ExecuteAsync(
        PgmCutsSequenceRequest request,
        Action<PgmCutsObservationStage>? observationStarting = null,
        CancellationToken cancellationToken = default)
    {
        ArgumentNullException.ThrowIfNull(request);
        if (!TryCreatePlan(request, out var plan))
        {
            return Empty("request-rejected");
        }

        if (!_hashPins.IsSatisfied())
        {
            return Empty("hash-pins-required") with
            {
                RequestValidated = true
            };
        }

        if (!_assetLeases.TryAcquire(plan!, out var assetLease) || assetLease is null)
        {
            return Empty("cut-assets-not-approved") with
            {
                RequestValidated = true,
                HashPinsPresent = true
            };
        }

        using var trustedAssets = assetLease;

        PgmDiagnosticTargetSnapshot baseline;
        try
        {
            baseline = _safetyProbe.Capture(plan!.DiagnosticRequest, plan.ParsedHost);
        }
        catch
        {
            return Empty("process-listener-inspection-unavailable") with
            {
                RequestValidated = true,
                HashPinsPresent = true
            };
        }

        if (!baseline.IsEligible)
        {
            return Empty("pgm-target-rejected") with
            {
                RequestValidated = true,
                HashPinsPresent = true
            };
        }

        IPlayoutEngine engine;
        try
        {
            engine = _engineFactory.Create(plan, baseline);
        }
        catch
        {
            return Empty("engine-creation-failed") with
            {
                RequestValidated = true,
                HashPinsPresent = true,
                TargetGatePassed = true
            };
        }

        var state = new ExecutionState();
        try
        {
            if (!await ExecuteCommandAsync(
                    engine,
                    plan,
                    baseline,
                    state,
                    PgmCutsSequenceStage.Connect,
                    () => engine.ConnectAsync(cancellationToken)).ConfigureAwait(false))
            {
                return state.ToReport();
            }

            if (!await ExecuteCommandAsync(
                    engine,
                    plan,
                    baseline,
                    state,
                    PgmCutsSequenceStage.PrepareFirst,
                    () => engine.PrepareAsync(plan.FirstCue, cancellationToken)).ConfigureAwait(false))
            {
                return state.ToReport();
            }

            if (!await ExecuteCommandAsync(
                    engine,
                    plan,
                    baseline,
                    state,
                    PgmCutsSequenceStage.TakeIn,
                    () => engine.TakeInAsync(cancellationToken)).ConfigureAwait(false))
            {
                return state.ToReport();
            }

            if (!await ObserveAsync(
                    engine,
                    plan,
                    baseline,
                    plan.ObservationDuration,
                    PgmCutsObservationStage.First,
                    observationStarting,
                    state,
                    cancellationToken).ConfigureAwait(false))
            {
                return state.ToReport();
            }

            if (!await ExecuteCommandAsync(
                    engine,
                    plan,
                    baseline,
                    state,
                    PgmCutsSequenceStage.Next,
                    () => engine.NextAsync(plan.NextCue, cancellationToken)).ConfigureAwait(false))
            {
                return state.ToReport();
            }

            if (!await ObserveAsync(
                    engine,
                    plan,
                    baseline,
                    plan.ObservationDuration,
                    PgmCutsObservationStage.Next,
                    observationStarting,
                    state,
                    cancellationToken).ConfigureAwait(false))
            {
                return state.ToReport();
            }

            if (!await ExecuteCommandAsync(
                    engine,
                    plan,
                    baseline,
                    state,
                    PgmCutsSequenceStage.TakeOut,
                    () => engine.TakeOutAsync(
                        PlayoutTakeOutScope.All,
                        cancellationToken)).ConfigureAwait(false))
            {
                return state.ToReport();
            }

            if (!await ObserveAsync(
                    engine,
                    plan,
                    baseline,
                    plan.ObservationDuration,
                    PgmCutsObservationStage.TakeOut,
                    observationStarting,
                    state,
                    cancellationToken).ConfigureAwait(false))
            {
                return state.ToReport();
            }

            if (!await ExecuteCommandAsync(
                    engine,
                    plan,
                    baseline,
                    state,
                    PgmCutsSequenceStage.Disconnect,
                    () => engine.DisconnectAsync(cancellationToken)).ConfigureAwait(false))
            {
                return state.ToReport();
            }

            state.Completed = true;
            return state.ToReport();
        }
        finally
        {
            if (!state.QuarantineAttempted || state.QuarantineCompleted)
            {
                try
                {
                    await engine.DisposeAsync().ConfigureAwait(false);
                }
                catch
                {
                    // Final local cleanup cannot erase the already classified safe report.
                }
            }
        }
    }

    private async Task<bool> ExecuteCommandAsync(
        IPlayoutEngine engine,
        PgmCutsSequencePlan plan,
        PgmDiagnosticTargetSnapshot baseline,
        ExecutionState state,
        PgmCutsSequenceStage stage,
        Func<Task<PlayoutResult>> command)
    {
        if (!HasSameTarget(plan, baseline))
        {
            state.OutcomeUnknown = state.Connected || state.OutputMayBeActive;
            await QuarantineAsync(engine, state, "pgm-target-changed").ConfigureAwait(false);
            return false;
        }

        PlayoutResult result;
        if (stage == PgmCutsSequenceStage.Disconnect)
        {
            state.DisconnectAttempted = true;
        }

        if (stage is PgmCutsSequenceStage.PrepareFirst or
            PgmCutsSequenceStage.TakeIn or
            PgmCutsSequenceStage.Next or
            PgmCutsSequenceStage.TakeOut)
        {
            state.RenderCommandAttempted = true;
        }

        try
        {
            result = await command().ConfigureAwait(false);
        }
        catch
        {
            _ = HasSameTarget(plan, baseline);
            state.OutcomeUnknown = true;
            await QuarantineAsync(engine, state, "command-outcome-unknown").ConfigureAwait(false);
            return false;
        }

        state.Commands.Add(new PgmCutsSequenceCommandReport(stage, result.Code));
        if (result.IsSuccess)
        {
            if (stage == PgmCutsSequenceStage.Connect)
            {
                state.Connected = true;
            }
            else if (stage == PgmCutsSequenceStage.TakeIn)
            {
                state.OutputMayBeActive = true;
            }
        }

        if (!HasSameTarget(plan, baseline))
        {
            if (stage != PgmCutsSequenceStage.Disconnect)
            {
                state.OutcomeUnknown =
                    state.Connected ||
                    state.OutputMayBeActive ||
                    (stage == PgmCutsSequenceStage.Connect && result.IsSuccess);
            }

            await QuarantineAsync(engine, state, "pgm-target-changed").ConfigureAwait(false);
            return false;
        }

        if (result.Code is PlayoutResultCode.OutcomeUnknown or PlayoutResultCode.TimedOut)
        {
            state.OutcomeUnknown = true;
            await QuarantineAsync(engine, state, "command-outcome-unknown").ConfigureAwait(false);
            return false;
        }

        if (stage == PgmCutsSequenceStage.Connect &&
            !result.IsSuccess &&
            engine.Status.KtapConnectAttempted)
        {
            state.OutcomeUnknown = true;
            await QuarantineAsync(engine, state, "command-outcome-unknown").ConfigureAwait(false);
            return false;
        }

        if (!result.IsSuccess)
        {
            state.ErrorCode = "command-not-completed";
            if (state.OutputMayBeActive || stage == PgmCutsSequenceStage.Disconnect)
            {
                state.OutcomeUnknown = true;
                await QuarantineAsync(engine, state, state.ErrorCode).ConfigureAwait(false);
            }
            else if (state.Connected)
            {
                await DisconnectAfterKnownFailureAsync(
                    engine,
                    plan,
                    baseline,
                    state).ConfigureAwait(false);
            }

            return false;
        }

        if (stage == PgmCutsSequenceStage.TakeOut)
        {
            state.OutputMayBeActive = false;
        }
        else if (stage == PgmCutsSequenceStage.Disconnect)
        {
            state.Connected = false;
        }

        return true;
    }

    private async Task DisconnectAfterKnownFailureAsync(
        IPlayoutEngine engine,
        PgmCutsSequencePlan plan,
        PgmDiagnosticTargetSnapshot baseline,
        ExecutionState state)
    {
        if (!HasSameTarget(plan, baseline))
        {
            state.OutcomeUnknown = state.Connected;
            await QuarantineAsync(engine, state, "pgm-target-changed").ConfigureAwait(false);
            return;
        }

        state.DisconnectAttempted = true;
        PlayoutResult disconnect;
        try
        {
            disconnect = await engine.DisconnectAsync(CancellationToken.None).ConfigureAwait(false);
        }
        catch
        {
            state.OutcomeUnknown = true;
            await QuarantineAsync(engine, state, "cleanup-outcome-unknown").ConfigureAwait(false);
            return;
        }

        state.Commands.Add(new PgmCutsSequenceCommandReport(
            PgmCutsSequenceStage.Disconnect,
            disconnect.Code));
        if (disconnect.IsSuccess)
        {
            state.Connected = false;
        }

        if (!HasSameTarget(plan, baseline))
        {
            state.OutcomeUnknown = state.Connected;
            await QuarantineAsync(engine, state, "pgm-target-changed").ConfigureAwait(false);
            return;
        }

        if (!disconnect.IsSuccess)
        {
            state.OutcomeUnknown = true;
            await QuarantineAsync(engine, state, "cleanup-outcome-unknown").ConfigureAwait(false);
        }
    }

    private async Task<bool> ObserveAsync(
        IPlayoutEngine engine,
        PgmCutsSequencePlan plan,
        PgmDiagnosticTargetSnapshot baseline,
        TimeSpan duration,
        PgmCutsObservationStage stage,
        Action<PgmCutsObservationStage>? observationStarting,
        ExecutionState state,
        CancellationToken cancellationToken)
    {
        if (!HasSameTarget(plan, baseline))
        {
            state.OutcomeUnknown = state.Connected || state.OutputMayBeActive;
            await QuarantineAsync(engine, state, "pgm-target-changed").ConfigureAwait(false);
            return false;
        }

        try
        {
            observationStarting?.Invoke(stage);
            await _delay.DelayAsync(duration, cancellationToken).ConfigureAwait(false);
        }
        catch
        {
            if (!HasSameTarget(plan, baseline))
            {
                state.OutcomeUnknown = state.Connected || state.OutputMayBeActive;
                await QuarantineAsync(engine, state, "pgm-target-changed").ConfigureAwait(false);
                return false;
            }

            state.ErrorCode = "observation-interrupted";
            if (state.OutputMayBeActive &&
                !await ExecuteCommandAsync(
                    engine,
                    plan,
                    baseline,
                    state,
                    PgmCutsSequenceStage.TakeOut,
                    () => engine.TakeOutAsync(
                        PlayoutTakeOutScope.All,
                        CancellationToken.None)).ConfigureAwait(false))
            {
                return false;
            }

            if (state.Connected)
            {
                _ = await ExecuteCommandAsync(
                    engine,
                    plan,
                    baseline,
                    state,
                    PgmCutsSequenceStage.Disconnect,
                    () => engine.DisconnectAsync(CancellationToken.None)).ConfigureAwait(false);
            }

            return false;
        }

        if (!HasSameTarget(plan, baseline))
        {
            state.OutcomeUnknown = state.Connected || state.OutputMayBeActive;
            await QuarantineAsync(engine, state, "pgm-target-changed").ConfigureAwait(false);
            return false;
        }

        return true;
    }

    private bool HasSameTarget(
        PgmCutsSequencePlan plan,
        PgmDiagnosticTargetSnapshot baseline)
    {
        try
        {
            var current = _safetyProbe.Capture(plan.DiagnosticRequest, plan.ParsedHost);
            return current.IsEligible && baseline.HasSameTarget(current);
        }
        catch
        {
            return false;
        }
    }

    private static async Task QuarantineAsync(
        IPlayoutEngine engine,
        ExecutionState state,
        string errorCode)
    {
        state.ErrorCode = errorCode;
        state.QuarantineAttempted = true;
        try
        {
            await engine.QuarantineAsync().ConfigureAwait(false);
            state.QuarantineCompleted = true;
        }
        catch
        {
            state.OutcomeUnknown = true;
        }
    }

    private static bool TryCreatePlan(
        PgmCutsSequenceRequest request,
        out PgmCutsSequencePlan? plan)
    {
        plan = null;
        var diagnosticRequest = new PgmConnectDiagnosticRequest(
            request.Host,
            request.Port,
            request.ExpectedPgmWindowTitle);
        if (request.ObservationMilliseconds != RequiredObservationMilliseconds ||
            !PgmConnectDiagnosticRunner.TryValidateRequest(diagnosticRequest, out var host) ||
            string.IsNullOrWhiteSpace(request.SceneRoot) ||
            !Path.IsPathFullyQualified(request.SceneRoot))
        {
            return false;
        }

        try
        {
            var options = ValidatedPlayoutOptions.Create(CreateOptions(request, host!));
            var firstCue = new PlayoutCue(
                $"{FirstSceneCode}.t2s",
                FirstSceneCode);
            var nextCue = new PlayoutCue(
                $"{NextSceneCode}.t2s",
                NextSceneCode);
            var firstAsset = options.ResolveCue(firstCue);
            var nextAsset = options.ResolveCue(nextCue);
            if (!IsTrustedLocalScenePaths(
                    options.SceneDirectory!,
                    firstAsset.SceneFile,
                    nextAsset.SceneFile))
            {
                return false;
            }

            plan = new PgmCutsSequencePlan(
                diagnosticRequest,
                host!,
                options,
                firstCue,
                nextCue,
                firstAsset.SceneFile,
                nextAsset.SceneFile,
                TimeSpan.FromMilliseconds(RequiredObservationMilliseconds));
            return true;
        }
        catch
        {
            return false;
        }
    }

    internal static bool IsTrustedLocalScenePaths(
        string sceneRoot,
        params string[] sceneFiles)
    {
        try
        {
            var fullRoot = Path.GetFullPath(sceneRoot);
            var pathRoot = Path.GetPathRoot(fullRoot);
            if (!Path.IsPathFullyQualified(fullRoot) ||
                string.IsNullOrEmpty(pathRoot) ||
                new DriveInfo(pathRoot).DriveType != DriveType.Fixed ||
                HasReparsePointInAncestry(new DirectoryInfo(fullRoot)))
            {
                return false;
            }

            var rootPrefix = fullRoot.EndsWith(Path.DirectorySeparatorChar)
                ? fullRoot
                : fullRoot + Path.DirectorySeparatorChar;
            foreach (var sceneFile in sceneFiles)
            {
                var fullFile = Path.GetFullPath(sceneFile);
                if (!fullFile.StartsWith(rootPrefix, StringComparison.OrdinalIgnoreCase) ||
                    !File.Exists(fullFile) ||
                    HasReparsePointInAncestry(new FileInfo(fullFile)))
                {
                    return false;
                }
            }

            return true;
        }
        catch
        {
            return false;
        }
    }

    private static bool HasReparsePointInAncestry(FileSystemInfo item)
    {
        FileSystemInfo? current = item;
        while (current is not null)
        {
            current.Refresh();
            if ((current.Attributes & FileAttributes.ReparsePoint) != 0)
            {
                return true;
            }

            current = current switch
            {
                FileInfo file => file.Directory,
                DirectoryInfo directory => directory.Parent,
                _ => null
            };
        }

        return false;
    }

    private static PlayoutOptions CreateOptions(
        PgmCutsSequenceRequest request,
        IPAddress host) => new()
    {
        Mode = PlayoutMode.Live,
        Host = host.ToString(),
        Port = request.Port,
        TcpMode = 1,
        ClientPort = 0,
        OutputChannel = null,
        LayoutIndex = K3dComConstants.LegacyLayoutIndex,
        SceneDirectory = request.SceneRoot,
        TestSceneAllowlist = [FirstSceneCode, NextSceneCode],
        TrustedLiveOutputEnabled = true,
        QueueCapacity = 8,
        ConnectTimeoutMilliseconds = 5_000,
        OperationTimeoutMilliseconds = 5_000,
        DisconnectTimeoutMilliseconds = 5_000,
        ProcessPollIntervalMilliseconds = 1_000,
        ReconnectDelayMilliseconds = 0,
        MaximumReconnectAttempts = 0,
        ReconnectEnabled = false
    };

    private static PgmCutsSequenceReport Empty(string errorCode) => new(
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        [],
        errorCode);

    private sealed class ExecutionState
    {
        public bool Connected { get; set; }
        public bool OutputMayBeActive { get; set; }
        public bool RenderCommandAttempted { get; set; }
        public bool DisconnectAttempted { get; set; }
        public bool QuarantineAttempted { get; set; }
        public bool QuarantineCompleted { get; set; }
        public bool Completed { get; set; }
        public bool OutcomeUnknown { get; set; }
        public string? ErrorCode { get; set; }
        public List<PgmCutsSequenceCommandReport> Commands { get; } = [];

        public PgmCutsSequenceReport ToReport() => new(
            true,
            true,
            true,
            true,
            RenderCommandAttempted,
            DisconnectAttempted,
            QuarantineAttempted,
            QuarantineCompleted,
            Completed,
            OutcomeUnknown,
            Commands.ToArray(),
            ErrorCode);
    }
}

internal sealed class ProcessPgmCutsSequenceHashPinRequirement : IPgmCutsSequenceHashPinRequirement
{
    public bool IsSatisfied()
    {
        byte[]? native = null;
        byte[]? interop = null;
        try
        {
            native = InstalledK3dInteropMetadata.ParseApprovedSha256(
                Environment.GetEnvironmentVariable(
                    InstalledK3dInteropMetadata.ApprovedNativeSha256EnvironmentVariable,
                    EnvironmentVariableTarget.Process));
            interop = InstalledK3dInteropMetadata.ParseApprovedSha256(
                Environment.GetEnvironmentVariable(
                    InstalledK3dInteropMetadata.ApprovedSha256EnvironmentVariable,
                    EnvironmentVariableTarget.Process));
            return true;
        }
        catch
        {
            return false;
        }
        finally
        {
            if (native is not null)
            {
                CryptographicOperations.ZeroMemory(native);
            }

            if (interop is not null)
            {
                CryptographicOperations.ZeroMemory(interop);
            }
        }
    }
}

internal sealed class FixedPgmCutsSequenceAssetLeaseFactory : IPgmCutsSequenceAssetLeaseFactory
{
    internal const string FirstApprovedSha256 =
        "99CE3B689A42D8C42BEB09A86FA10C2D7C1AEF4F50D324D81276C1A1E4C4D8A7";
    internal const string NextApprovedSha256 =
        "25CD0AE931F51E4E3B84CE3E6FD21A40DB85464F157A23CC3511D63B336D8757";

    public bool TryAcquire(
        PgmCutsSequencePlan plan,
        out IPgmCutsSequenceAssetLease? lease)
    {
        ArgumentNullException.ThrowIfNull(plan);
        lease = null;
        FileStream? first = null;
        FileStream? next = null;
        try
        {
            if (!PgmCutsSequenceRunner.IsTrustedLocalScenePaths(
                    plan.Options.SceneDirectory!,
                    plan.FirstAssetPath,
                    plan.NextAssetPath) ||
                !TryOpenApproved(
                    plan.FirstAssetPath,
                    FirstApprovedSha256,
                    out first) ||
                !TryOpenApproved(
                    plan.NextAssetPath,
                    NextApprovedSha256,
                    out next) ||
                !PgmCutsSequenceRunner.IsTrustedLocalScenePaths(
                    plan.Options.SceneDirectory!,
                    plan.FirstAssetPath,
                    plan.NextAssetPath))
            {
                return false;
            }

            lease = new FixedPgmCutsSequenceAssetLease(first!, next!);
            first = null;
            next = null;
            return true;
        }
        catch
        {
            return false;
        }
        finally
        {
            next?.Dispose();
            first?.Dispose();
        }
    }

    internal static bool HasExpectedSha256(Stream stream, string expectedHex)
    {
        ArgumentNullException.ThrowIfNull(stream);
        byte[]? actual = null;
        byte[]? expected = null;
        try
        {
            expected = Convert.FromHexString(expectedHex);
            if (expected.Length != SHA256.HashSizeInBytes)
            {
                return false;
            }

            if (stream.CanSeek)
            {
                stream.Position = 0;
            }

            actual = SHA256.HashData(stream);
            return CryptographicOperations.FixedTimeEquals(actual, expected);
        }
        catch
        {
            return false;
        }
        finally
        {
            if (actual is not null)
            {
                CryptographicOperations.ZeroMemory(actual);
            }

            if (expected is not null)
            {
                CryptographicOperations.ZeroMemory(expected);
            }
        }
    }

    private static bool TryOpenApproved(
        string path,
        string expectedSha256,
        out FileStream? stream)
    {
        stream = null;
        try
        {
            stream = new FileStream(
                path,
                FileMode.Open,
                FileAccess.Read,
                FileShare.Read,
                bufferSize: 64 * 1024,
                FileOptions.SequentialScan);
            if (HasExpectedSha256(stream, expectedSha256))
            {
                return true;
            }
        }
        catch
        {
            // The caller treats any asset inspection failure as rejection.
        }

        stream?.Dispose();
        stream = null;
        return false;
    }

    private sealed class FixedPgmCutsSequenceAssetLease(
        FileStream first,
        FileStream next) : IPgmCutsSequenceAssetLease
    {
        private FileStream? _first = first;
        private FileStream? _next = next;

        public void Dispose()
        {
            Interlocked.Exchange(ref _next, null)?.Dispose();
            Interlocked.Exchange(ref _first, null)?.Dispose();
        }
    }
}

internal sealed class SystemPgmCutsSequenceDelay : IPgmCutsSequenceDelay
{
    public Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken) =>
        Task.Delay(delay, cancellationToken);
}

internal sealed class FullPgmCutsSequenceEngineFactory : IPgmCutsSequenceEngineFactory
{
    private readonly IPgmDiagnosticSafetyProbe _safetyProbe;

    public FullPgmCutsSequenceEngineFactory(IPgmDiagnosticSafetyProbe safetyProbe)
    {
        _safetyProbe = safetyProbe;
    }

    public IPlayoutEngine Create(
        PgmCutsSequencePlan plan,
        PgmDiagnosticTargetSnapshot baseline)
    {
        bool HasExactTarget()
        {
            try
            {
                var current = _safetyProbe.Capture(
                    plan.DiagnosticRequest,
                    plan.ParsedHost);
                return current.IsEligible && baseline.HasSameTarget(current);
            }
            catch
            {
                return false;
            }
        }

        var dispatcher = new StaDispatcher(plan.Options.QueueCapacity);
        try
        {
            return new TornadoPlayoutEngine(
                plan.Options,
                new DynamicK3dSessionFactory(),
                new K3dRegistrationProbe(),
                new PgmCutsSequenceProcessProbe(
                    _safetyProbe,
                    plan.DiagnosticRequest,
                    plan.ParsedHost,
                    baseline),
                dispatcher,
                PgmCutsSequenceLiveAuthorization.Instance,
                TimeProvider.System,
                startMonitor: false,
                finalConnectSafetyCheck: HasExactTarget,
                abandonOnTargetMismatch: true);
        }
        catch
        {
            dispatcher.DisposeAsync().AsTask().GetAwaiter().GetResult();
            throw;
        }
    }

    private sealed class PgmCutsSequenceLiveAuthorization : ILiveAuthorization
    {
        private PgmCutsSequenceLiveAuthorization()
        {
        }

        public static PgmCutsSequenceLiveAuthorization Instance { get; } = new();

        public bool IsAuthorizedForThisLaunch => true;
    }
}

internal sealed class PgmCutsSequenceProcessProbe : ITornadoProcessProbe
{
    private readonly IPgmDiagnosticSafetyProbe _safetyProbe;
    private readonly PgmConnectDiagnosticRequest _request;
    private readonly IPAddress _host;
    private readonly PgmDiagnosticTargetSnapshot _baseline;

    public PgmCutsSequenceProcessProbe(
        IPgmDiagnosticSafetyProbe safetyProbe,
        PgmConnectDiagnosticRequest request,
        IPAddress host,
        PgmDiagnosticTargetSnapshot baseline)
    {
        _safetyProbe = safetyProbe;
        _request = request;
        _host = host;
        _baseline = baseline;
    }

    public TornadoProcessSnapshot Capture(System.Text.RegularExpressions.Regex? testWindowPattern)
    {
        try
        {
            var current = _safetyProbe.Capture(_request, _host);
            if (!current.IsEligible || !_baseline.HasSameTarget(current) ||
                current.Identity is not { } identity)
            {
                return Unavailable();
            }

            var generation = TornadoProcessGeneration.FromIdentities(
                "pgm-cuts-sequence",
                [new TornadoProcessIdentity(identity.ProcessId, identity.StartTimeUtcTicks)]);
            return new TornadoProcessSnapshot(1, 1, 0)
            {
                EligibleProcessGeneration = generation,
                ProgramProcessGeneration = TornadoProcessGeneration.Synthetic("program", 0),
                IdentityInspectionSucceeded = true
            };
        }
        catch
        {
            return Unavailable();
        }
    }

    private static TornadoProcessSnapshot Unavailable() => new(0, 0, 0)
    {
        IdentityInspectionSucceeded = false
    };
}
