# ============================================================
# src/accountable_record/stage_010_identity/transform.py
# ============================================================
"""s010 identity stage transform.

WHY:
    Adapts identity 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 transform validates the target repository declared by the run context,
    then folds the produced identity artifact and diagnostics into the
    accumulated pipeline 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_010_identity.validation import validate_identity_stage

STAGE_CODE = "s010"


@stage(STAGE_CODE, Concern.IDENTITY, "Validate repository identity metadata.")
def transform_identity(state: PipelineState) -> PipelineState:
    """Validate the target repository identity and accumulate the result."""
    result = validate_identity_stage(
        state.context.target_root,
        expected=state.context.expected,
    )

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

    return state.with_identity(result.identity, result.diagnostics)
