namespace KArtSell.Modules.ModelOperations.Domain;

public enum ModelOperationCadence
{
    Daily,
    Weekly,
    Monthly,
    Quarterly,
    EventDriven
}

public enum AutomationMode
{
    EvaluationOnly,
    ProposalOnly,
    DrillOnly
}

public static class ModelOperationContractValues
{
    public static string ToContractValue(this AutomationMode mode) => mode switch
    {
        AutomationMode.EvaluationOnly => "EVALUATION_ONLY",
        AutomationMode.ProposalOnly => "PROPOSAL_ONLY",
        AutomationMode.DrillOnly => "DRILL_ONLY",
        _ => throw new ArgumentOutOfRangeException(nameof(mode), mode, null)
    };

    public static string ToContractValue(this ModelOperationCadence cadence) => cadence switch
    {
        ModelOperationCadence.Daily => "DAILY",
        ModelOperationCadence.Weekly => "WEEKLY",
        ModelOperationCadence.Monthly => "MONTHLY",
        ModelOperationCadence.Quarterly => "QUARTERLY",
        ModelOperationCadence.EventDriven => "EVENT_DRIVEN",
        _ => throw new ArgumentOutOfRangeException(nameof(cadence), cadence, null)
    };
}

public sealed record ModelOperationDefinition(
    string OperationCode,
    string Name,
    ModelOperationCadence Cadence,
    AutomationMode AutomationMode,
    string Queue,
    string PrimaryOwner,
    string SecondaryOwner,
    string RequiredEvidence,
    string Output,
    string Gate);

public static class ModelOperationRegistry
{
    public static IReadOnlyList<ModelOperationDefinition> All { get; } =
    [
        new("J10", "OutcomeEvaluationRun", ModelOperationCadence.Daily, AutomationMode.EvaluationOnly,
            "q-evaluation", "Quant/Ops", "Data/QA", "due 1/5/20/63/126/252 windows", "versioned outcome observations", "G3"),
        new("J11", "DailyScorecardBuild", ModelOperationCadence.Daily, AutomationMode.EvaluationOnly,
            "q-evaluation", "Quant/Ops", "Risk/SRE", "completed outcomes and operational metrics", "daily cohort scorecard", "G3"),
        new("J17", "DriftDetectionRun", ModelOperationCadence.Daily, AutomationMode.EvaluationOnly,
            "q-evaluation", "Quant/Risk", "Data/SRE", "feature, prediction and data-quality baselines", "drift observations and hold alerts", "G4"),
        new("J18", "ChampionChallengerEvaluation", ModelOperationCadence.Weekly, AutomationMode.EvaluationOnly,
            "q-evaluation", "Quant/Risk", "QA/InvestmentCommittee", "same frozen data, cost and cohort definitions", "paired champion/challenger comparison", "G4"),
        new("J19", "FrozenOosBacktest", ModelOperationCadence.Monthly, AutomationMode.EvaluationOnly,
            "q-research", "Quant/Data", "QA/Risk", "dataset, code, config, seed and environment manifest", "walk-forward OOS evidence bundle", "G4"),
        new("J20", "RobustnessPboDsrRun", ModelOperationCadence.Quarterly, AutomationMode.EvaluationOnly,
            "q-research", "Quant/Risk", "IndependentValidation", "experiment registry, CSCV and block-bootstrap inputs", "PBO/DSR/stability/cost-stress report", "G4"),
        new("J21", "ModelImprovementProposalBuild", ModelOperationCadence.Monthly, AutomationMode.ProposalOnly,
            "q-research", "Quant Lead", "Risk/Architect", "scorecard, drift, attribution and debt evidence", "review-required improvement proposal", "G4"),
        new("J22", "PromotionEvidenceReviewBuild", ModelOperationCadence.Monthly, AutomationMode.ProposalOnly,
            "q-control", "Risk/InvestmentCommittee", "Compliance/QA", "all promotion-gate evidence and independent validation", "maker-checker review packet", "G4"),
        new("J23", "ModelRollbackDrill", ModelOperationCadence.Quarterly, AutomationMode.DrillOnly,
            "q-control", "SRE/Risk", "Module Owner/QA", "approved champion manifest and rollback runbook", "rollback drill evidence", "G5"),
        new("J24", "DataRevisionRevalidation", ModelOperationCadence.Weekly, AutomationMode.EvaluationOnly,
            "q-backfill", "Data/Quant", "DBA/QA", "revision lineage and affected-decision index", "replay impact and correction proposal", "G3"),
        new("J25", "SourceContractDriftCheck", ModelOperationCadence.Daily, AutomationMode.EvaluationOnly,
            "q-evaluation", "Data Governance", "Adapter Owner/QA", "approved source schema, license and SLA snapshot", "source contract drift evidence and hold", "G1"),
        new("J26", "MarketCalendarCompletenessCheck", ModelOperationCadence.Daily, AutomationMode.EvaluationOnly,
            "q-market-data", "Data/Ops", "Quant/QA", "approved KRX/NYSE/NASDAQ calendar and source completeness", "tradable-session readiness evidence", "G1"),
        new("J27", "EvidenceChainAudit", ModelOperationCadence.Daily, AutomationMode.EvaluationOnly,
            "q-control", "Compliance/QA", "Data/BE", "decision-to-source hash chain and immutable audit records", "missing-link and mutation evidence", "G3"),
        new("J28", "ProjectionFreshnessCheck", ModelOperationCadence.Daily, AutomationMode.EvaluationOnly,
            "q-evaluation", "BE/Data", "SRE/QA", "projection version, watermark and rebuild contract", "staleness and rebuild-diff evidence", "G3"),
        new("J29", "CapacitySlaTrend", ModelOperationCadence.Weekly, AutomationMode.EvaluationOnly,
            "q-control", "SRE/PM", "DBA/Module Owner", "approved volume assumptions and SLO definitions", "capacity trend and scaling decision packet", "G5"),
        new("J30", "ReleaseEvidenceAssemble", ModelOperationCadence.EventDriven, AutomationMode.ProposalOnly,
            "q-control", "QA/Release Manager", "Compliance/SRE", "approved build, test, migration, security and rollback artifacts", "review-required release evidence bundle", "G6"),
        new("J31", "PredictionFreezeRun", ModelOperationCadence.Daily, AutomationMode.EvaluationOnly,
            "q-evaluation", "Quant/Data", "QA/Risk", "approved PIT context before market cutoff", "immutable prediction freeze and VersionSet hash", "G3"),
        new("J32", "OutcomeMaturitySweep", ModelOperationCadence.Daily, AutomationMode.EvaluationOnly,
            "q-evaluation", "Quant/Ops", "Data/QA", "trading-session calendar and due evaluation windows", "matured 1/5/20/63/126/252 evaluation requests", "G3"),
        new("J33", "SellReentryAttributionReview", ModelOperationCadence.Weekly, AutomationMode.EvaluationOnly,
            "q-evaluation", "Quant/Risk", "Advisor/QA", "matured sell and reentry outcomes with cost and benchmark", "false-exit, gain-capture, capture-rate and delay-cost evidence", "G4"),
        new("J34", "CalibrationRegimeReview", ModelOperationCadence.Weekly, AutomationMode.EvaluationOnly,
            "q-evaluation", "Quant/Risk", "Data/IndependentValidation", "versioned cohort, regime and prediction distribution definitions", "calibration, coverage, drift and regime stability evidence", "G4"),
        new("J35", "ImprovementHypothesisBuild", ModelOperationCadence.Monthly, AutomationMode.ProposalOnly,
            "q-research", "Quant Lead", "Risk/Architect", "scorecard, attribution, drift, incidents and debt evidence", "review-required improvement hypothesis with falsification test", "G4"),
        new("J36", "ChallengerExperimentPlan", ModelOperationCadence.Monthly, AutomationMode.ProposalOnly,
            "q-research", "Quant Lead", "IndependentValidation/QA", "approved hypothesis and frozen experiment registry", "review-required challenger experiment plan; no activation", "G4"),
        new("J37", "IndependentValidationPack", ModelOperationCadence.Quarterly, AutomationMode.ProposalOnly,
            "q-control", "IndependentValidation", "Risk/Compliance", "OOS, PBO, DSR, cost stress, reproducibility and operations evidence", "independent validation decision packet", "G4"),
        new("J38", "ModelPolicyDebtReview", ModelOperationCadence.Monthly, AutomationMode.ProposalOnly,
            "q-control", "Risk/Architect", "Quant/PM", "model, policy, data and technical debt register", "prioritized remediation and expiration decisions", "G5"),
        new("J39", "FeedbackCycleIntegrityAudit", ModelOperationCadence.Daily, AutomationMode.EvaluationOnly,
            "q-control", "Compliance/QA", "Quant/SRE", "feedback-cycle state, transition sequence, evidence hashes and aging policy", "stuck-cycle, illegal-transition and evidence-gap report", "G4"),
        new("J40", "EvaluationWindowIntegrityAudit", ModelOperationCadence.Daily, AutomationMode.EvaluationOnly,
            "q-control", "Quant/QA", "Data/SRE", "prediction evidence, approved trading calendar and 1/5/20/63/126/252 window plan", "missing, duplicate, late and calendar-drift window report", "G4"),
        new("J41", "SchedulerLeaseIntegrityAudit", ModelOperationCadence.Daily, AutomationMode.EvaluationOnly,
            "q-control", "SRE/QA", "BE/DBA", "schedule leases, fencing tokens, heartbeat and dispatch revisions", "expired, overlapping and stale-token lease report", "G3"),
        new("J42", "ModelEvaluationReconciliation", ModelOperationCadence.Daily, AutomationMode.EvaluationOnly,
            "q-evaluation", "Quant/QA", "Data/Risk", "prediction windows, outcomes, source revisions and metric definitions", "missing, duplicate, late and revision-recalculation plan", "G4")
    ];

    public static ModelOperationDefinition GetRequired(string operationCode)
        => All.SingleOrDefault(x => x.OperationCode.Equals(operationCode, StringComparison.OrdinalIgnoreCase))
           ?? throw new ArgumentOutOfRangeException(nameof(operationCode), operationCode, "Unknown model operation code.");
}
