# ============================================================
# src/accountable_record/stage_020_contract/transform.py
# ============================================================
"""s020 contract stage transform.

WHY:
    Adapts contract-context validation to the pipeline transform contract
    (PipelineState -> PipelineState). Registration is co-located here via
    @stage so the pipeline map points directly at the function it runs, the
    same pattern stage 010 uses.

    The transform reads the identity established by stage 010 from the
    accumulated state, validates the target's contract declaration against it,
    then folds the produced contract context and diagnostics into the state.
"""

from accountable_record.pipeline.context import PipelineState
from accountable_record.pipeline.diagnostics import Concern
from accountable_record.pipeline.stages import stage
from accountable_record.stage_020_contract.validation import (
    validate_contract_stage,
)

STAGE_CODE = "s020"


@stage(STAGE_CODE, Concern.CONTRACT, "Establish and validate contract context.")
def transform_contract(state: PipelineState) -> PipelineState:
    """Validate the target contract context and accumulate the result.

    OBS:
        The identity version comes from the stage 010 artifact carried in
        state. Stage 020 does not re-read identity; it consumes what the
        upstream stage already established, which is the whole point of the
        one-way accumulated pipeline.
    """
    result = validate_contract_stage(state)

    if result.has_errors or result.contract is None:
        return state.with_failure(STAGE_CODE, result.diagnostics)

    return state.with_contract(result.contract, result.diagnostics)
