"""Typed errors so the API can return clean, specific JSON."""

from __future__ import annotations


class OrchestratorError(Exception):
    """Base class for every orchestrator error."""

    status = 500
    code = "orchestrator_error"


class ValidationError(OrchestratorError):
    status = 400
    code = "bad_request"


class NotFound(OrchestratorError):
    """A referenced record (lead, draft, ...) does not exist."""

    status = 404
    code = "not_found"


class JobNotFound(OrchestratorError):
    status = 404
    code = "not_found"


class IllegalTransition(OrchestratorError):
    status = 409
    code = "illegal_transition"

    def __init__(self, message: str, allowed: list[str] | None = None):
        super().__init__(message)
        self.allowed = allowed or []


class VerificationBlocked(OrchestratorError):
    """The immune-system gate: the facts did not survive re-checking.

    Raised by BOTH the verification component and the state-machine transition
    boundary, so a buggy component cannot wave an unverified claim through.
    """

    status = 409
    code = "verification_failed"

    def __init__(
        self,
        message: str,
        verdict: str | None = None,
        details: dict | None = None,
    ):
        super().__init__(message)
        self.verdict = verdict
        self.details = details or {}


class BotBuildBlocked(OrchestratorError):
    """The bot factory refused to build: the opportunity is not VERIFIED.

    Raised by BOTH the factory component and the state-machine boundary
    (``VERIFIED -> BOT_BUILT``), so a replaced or buggy component cannot build a
    spec from an unverified opportunity.
    """

    status = 409
    code = "bot_build_refused"

    def __init__(
        self,
        message: str,
        verdict: str | None = None,
        details: dict | None = None,
    ):
        super().__init__(message)
        self.verdict = verdict
        self.details = details or {}


class MeasurementBlocked(OrchestratorError):
    """No keep-or-kill verdict can be produced from the evidence available.

    Raised when a job reaches MEASURED with no bot spec, no measurement, or a
    measurement that is still INCONCLUSIVE. The job stays at MEASURED.
    """

    status = 409
    code = "measurement_blocked"

    def __init__(
        self,
        message: str,
        verdict: str | None = None,
        details: dict | None = None,
    ):
        super().__init__(message)
        self.verdict = verdict
        self.details = details or {}


class NoComponent(OrchestratorError):
    status = 503
    code = "no_component"


class RegistryError(OrchestratorError):
    status = 500
    code = "registry_error"
