"""Canonical worker artifact path derivation."""
from __future__ import annotations


class WorkerArtifactPathError(ValueError):
    """Raised when a worker artifact path is not canonical."""


def audit_sidecar_rel(worker_result_rel: str) -> str:
    """Insert `-audit-` after the first canonical `-worker-` token."""
    if not worker_result_rel.endswith(".md"):
        raise WorkerArtifactPathError(
            f"worker result path must end with .md: {worker_result_rel}"
        )
    directory, slash, filename = worker_result_rel.rpartition("/")
    basename = filename if slash else worker_result_rel
    prefix, separator, suffix = basename.partition("-worker-")
    if not separator:
        raise WorkerArtifactPathError(
            "worker result path has no canonical -worker- token: "
            f"{worker_result_rel}. The audit sidecar is derived from the "
            "canonical worker-result name `<role>-worker-<task-type>-<seq>.md` "
            "(e.g. `codex-worker-implementation-001.md`); name the result that "
            "way — a role label like `codex-verifier-...` drops the -worker- token."
        )
    audit_filename = f"{prefix}-worker-audit-{suffix}"
    return f"{directory}{slash}{audit_filename}" if slash else audit_filename
