# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-subcontract-bid-whose-capability-token-it-cannot-re-verify-at-the-moment-of-award.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-subcontract-bid-whose-capability-token-it-cannot-re-verify-at-the-moment-of-award.warrant.json
# Markdown SHA-256:   c077cf68104be65a82a6c8cbe78308aa6af3239eaab99e80c19bfaa4b0d7158e
# Code AST SHA-256:   58ad02025a3eea5e8ce104a26591d06c6004502c49dc60aaa5acb7fd6c5e060b
# Verified Classes:   AuthorityUnverifiableAtAward, WarrantClass, VerifyResult, Bid, CFP
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass
from enum import Enum


class AuthorityUnverifiableAtAward(RuntimeError):
    """Raised when a subcontract bid's warrant cannot be re-verified at award time
    and the fail-deferred preconditions are not all satisfied."""


class WarrantClass(Enum):
    BEARER = "bearer"
    PROOF_OF_AUTHORITY = "proof_of_authority"


class VerifyResult(Enum):
    VERIFIED = "verified"
    REVOKED = "revoked"
    UNREACHABLE = "unreachable"


@dataclass
class Bid:
    agent_id: str
    price: float
    warrant_ttl_at_award: float  # seconds remaining at t_award
    warrant_class: WarrantClass
    schema_hash: str
    result_schema_has_authority_status: bool


@dataclass
class CFP:
    required_schema_hash: str
    expected_execution_time: float
    task_replayable: bool


def award(
    cfp: CFP,
    bid: Bid,
    verify: VerifyResult,
    ledger_verify: VerifyResult | None,
) -> str:
    """Resolve an award to VERIFIED, DEFERRED_BOUNDED, or REJECTED.
    Raises AuthorityUnverifiableAtAward on the silent-laundering path."""
    if bid.schema_hash != cfp.required_schema_hash:
        return "REJECTED:SCHEMA_MISMATCH"

    if bid.warrant_ttl_at_award <= cfp.expected_execution_time:
        return "REJECTED:TTL_EXPIRES_MID_EXECUTION"

    if verify is VerifyResult.REVOKED:
        return "REJECTED:REVOKED_AT_AWARD"

    if verify is VerifyResult.VERIFIED:
        return "VERIFIED"

    # verify is UNREACHABLE: only defer under all three preconditions
    if (
        cfp.task_replayable
        and bid.result_schema_has_authority_status
        and bid.warrant_class is WarrantClass.PROOF_OF_AUTHORITY
        and ledger_verify is VerifyResult.VERIFIED
    ):
        return "DEFERRED_BOUNDED"

    raise AuthorityUnverifiableAtAward(
        f"bidder={bid.agent_id} warrant unreachable at award; "
        f"replayable={cfp.task_replayable} "
        f"authority_signaled={bid.result_schema_has_authority_status} "
        f"class={bid.warrant_class.value} "
        f"ledger={ledger_verify} -> must fail-closed, re-award to next bidder"
    )


def ingest_result(
    award_state: str,
    result: dict,
    reverify_deadline: float,
    now: float,
) -> dict:
    """Gate result ingestion; deferred awards must pass a re-verify gate
    and the result must carry authority_status before mutating manager state."""
    if award_state == "DEFERRED_BOUNDED":
        if now > reverify_deadline:
            raise AuthorityUnverifiableAtAward(
                "deferred re-verify deadline exceeded before result ingestion"
            )
        if "authority_status" not in result:
            raise AuthorityUnverifiableAtAward(
                "deferred award result lacks authority_status; cannot distinguish "
                "success from rejected-authority no-op"
            )
        if result["authority_status"] != "granted":
            raise AuthorityUnverifiableAtAward(
                f"authority rejected at execution: {result['authority_status']}"
            )
    return result
