namespace KArtSell.Modules.SignalEngine.Domain;

public enum ReentryState
{
    Watching,
    Ready,
    Reentered,
    Open,
    Expired,
    Closed
}

public sealed record ReentryInput(
    int SessionsSinceSell,
    int SessionsSinceLastStage,
    bool RisingSma50Reclaimed,
    bool Prior20SessionHighBroken,
    bool AdditionalAssetConfirmationPassed,
    bool HardImpairment,
    bool Expired,
    bool StageExecuted = false,
    bool HasRemainingStages = false);

public static class ReentryStateMachine
{
    public static ReentryState Evaluate(ReentryState current, ReentryInput input)
    {
        if (input.HardImpairment)
        {
            return ReentryState.Closed;
        }

        if (input.Expired && current is not ReentryState.Open)
        {
            return ReentryState.Expired;
        }

        if (current is ReentryState.Expired or ReentryState.Closed or ReentryState.Open)
        {
            return current;
        }

        if (current is ReentryState.Ready && input.StageExecuted)
        {
            return ReentryState.Reentered;
        }

        if (current is ReentryState.Reentered)
        {
            return input.HasRemainingStages ? ReentryState.Watching : ReentryState.Open;
        }

        var ready = input.SessionsSinceSell >= 10
                    && input.SessionsSinceLastStage >= 10
                    && input.RisingSma50Reclaimed
                    && input.Prior20SessionHighBroken
                    && input.AdditionalAssetConfirmationPassed;

        return ready ? ReentryState.Ready : ReentryState.Watching;
    }
}
