"""The core loop, modelled as an explicit state machine.

    INGESTED -> VERIFIED -> BOT_BUILT -> RUNNING -> MEASURED -> KEPT | KILLED

FAILED and REJECTED are terminal states reachable from any non-terminal state.
There is no implicit "next state": every edge below is the complete legal set,
and anything else is rejected with an IllegalTransition.
"""

from __future__ import annotations

from .errors import IllegalTransition

# --- states ---------------------------------------------------------------

INGESTED = "INGESTED"
VERIFIED = "VERIFIED"
BOT_BUILT = "BOT_BUILT"
RUNNING = "RUNNING"
MEASURED = "MEASURED"
KEPT = "KEPT"
KILLED = "KILLED"
FAILED = "FAILED"
REJECTED = "REJECTED"

#: The six loop states, in order, as shown on the dashboard pipeline.
PIPELINE_STATES = [INGESTED, VERIFIED, BOT_BUILT, RUNNING, MEASURED, KEPT]

#: The five states a job can still move out of.
ACTIVE_STATES = [INGESTED, VERIFIED, BOT_BUILT, RUNNING, MEASURED]

#: Terminal states: no outgoing edges, ever.
TERMINAL_STATES = [KEPT, KILLED, FAILED, REJECTED]

ALL_STATES = PIPELINE_STATES + [KILLED, FAILED, REJECTED]

#: The complete transition table. This is the single source of truth.
TRANSITIONS: dict[str, list[str]] = {
    INGESTED: [VERIFIED, FAILED, REJECTED],
    VERIFIED: [BOT_BUILT, FAILED, REJECTED],
    BOT_BUILT: [RUNNING, FAILED, REJECTED],
    RUNNING: [MEASURED, FAILED, REJECTED],
    MEASURED: [KEPT, KILLED, FAILED, REJECTED],
    KEPT: [],
    KILLED: [],
    FAILED: [],
    REJECTED: [],
}

#: Human labels for the pipeline strip.
STATE_LABELS = {
    INGESTED: "ingested",
    VERIFIED: "verified",
    BOT_BUILT: "bot built",
    RUNNING: "running",
    MEASURED: "measured",
    KEPT: "kept",
    KILLED: "killed",
    FAILED: "failed",
    REJECTED: "rejected",
}


def is_state(state: str) -> bool:
    return state in TRANSITIONS


def is_terminal(state: str) -> bool:
    return state in TERMINAL_STATES


def allowed_from(state: str) -> list[str]:
    return list(TRANSITIONS.get(state, []))


def can_transition(from_state: str, to_state: str) -> bool:
    return to_state in TRANSITIONS.get(from_state, [])


def assert_transition(from_state: str, to_state: str) -> None:
    """Raise IllegalTransition unless from_state -> to_state is a legal edge."""
    if not is_state(from_state):
        raise IllegalTransition(f"unknown state {from_state!r}", allowed=[])
    if not is_state(to_state):
        raise IllegalTransition(f"unknown target state {to_state!r}", allowed=allowed_from(from_state))
    if not can_transition(from_state, to_state):
        allowed = allowed_from(from_state)
        if not allowed:
            raise IllegalTransition(
                f"illegal transition {from_state} -> {to_state}: {from_state} is terminal "
                f"and has no outgoing transitions",
                allowed=[],
            )
        raise IllegalTransition(
            f"illegal transition {from_state} -> {to_state}; "
            f"from {from_state} the only legal targets are: {', '.join(allowed)}",
            allowed=allowed,
        )


def assert_verification_gate(
    from_state: str,
    to_state: str,
    *,
    cites_signals: bool,
    verdict: str | None,
    rule_version: str | None = None,
    citations: list[dict] | None = None,
    blocking_signal_ids: list[str] | None = None,
    opportunity_id: str | None = None,
    job_id: str | None = None,
) -> None:
    """THE IMMUNE-SYSTEM GATE, enforced at the transition boundary.

    A job that cites signals makes a factual claim. It may only move INTO a
    fact-claiming state (VERIFIED, BOT_BUILT) when the stored verdict for those
    citations is exactly ``VERIFIED``.

    This lives in the state machine — not only in the verifier — so that a
    replaced, patched or buggy component cannot bypass the check: ``advance()``
    calls this after the component returns and before the row is written, and it
    rolls the transition back with a 409.

    Plain manual/seed jobs that cite nothing are out of scope: they make no
    factual claim, so there is nothing to gate (the verifier says so in its note).
    """
    from .errors import VerificationBlocked

    GATED_TARGETS = (VERIFIED, BOT_BUILT)
    if to_state not in GATED_TARGETS or not cites_signals:
        return
    if verdict == VERIFIED:
        return

    citations = citations or []
    named = blocking_signal_ids or [
        c.get("signal_id") for c in citations if c.get("outcome") != "confirmed"
    ]
    by_id = {c.get("signal_id"): c for c in citations}
    blocking = []
    for sid in named:
        c = by_id.get(sid)
        if c:
            blocking.append(
                f"{sid} {c.get('source')} {c.get('url')} -> {c.get('outcome')}: "
                f"{c.get('saw') or c.get('error') or 'no detail'}"
            )
    where = opportunity_id or f"job {str(job_id)[:8]}"
    message = (
        f"verification gate refused {from_state} -> {to_state} for {where}: "
        f"verdict is {verdict or 'NO VERDICT'}"
        + (f" (rule v{rule_version})" if rule_version else "")
        + ". Only a VERIFIED verdict may advance."
    )
    if blocking:
        message += " Blocking citations: " + "; ".join(blocking[:6])
    elif not citations:
        message += (
            " No verification evidence is recorded for this opportunity — run "
            "POST /opportunities/<id>/verify first."
        )
    raise VerificationBlocked(
        message,
        verdict=verdict,
        details={
            "verdict": verdict,
            "rule_version": rule_version,
            "opportunity_id": opportunity_id,
            "blocking_signal_ids": named,
            "citations": citations,
        },
    )


def assert_bot_build_gate(
    from_state: str,
    to_state: str,
    *,
    verdict: str | None,
    opportunity_id: str | None = None,
    job_id: str | None = None,
) -> None:
    """THE BOT-FACTORY GATE, enforced at the transition boundary.

    Building a bot is a commitment: it turns a claim into an artifact with a cost
    and a value. So the same rule as the verification gate applies, one step
    later — a spec may only be produced from an opportunity whose stored verdict
    is exactly ``VERIFIED``.

    It lives in the state machine, not only in the factory, so that a replaced,
    patched or buggy component cannot bypass it: ``service.advance()`` calls this
    after the component returns and before the row is written, and rolls the
    transition back with a 409.

    A job that carries no opportunity at all (a plain manual/seed job) has
    nothing to build from — there are no scores and no verdict — and is refused
    for that reason rather than getting an invented spec.
    """
    from .errors import BotBuildBlocked

    if to_state != BOT_BUILT:
        return
    if verdict == VERIFIED:
        return

    where = opportunity_id or f"job {str(job_id)[:8]}"
    if verdict is None:
        message = (
            f"bot factory refused {from_state} -> {to_state} for {where}: no verification "
            f"verdict exists for this opportunity, so there is nothing VERIFIED to build from. "
            f"Run POST /opportunities/<id>/verify first."
        )
    else:
        message = (
            f"bot factory refused {from_state} -> {to_state} for {where}: verdict is "
            f"{verdict}, not VERIFIED. Only a VERIFIED opportunity may become a bot spec."
        )
    raise BotBuildBlocked(
        message,
        verdict=verdict,
        details={
            "verdict": verdict,
            "opportunity_id": opportunity_id,
            "job_id": job_id,
            "rule": "bot builds require a stored VERIFIED verdict (enforced in the component "
                    "and at the state-machine boundary)",
        },
    )


def next_state(state: str) -> str | None:
    """The happy-path successor, or None for terminal / ambiguous states."""
    if state == MEASURED:
        return None  # decided by the Decision component, not by the table
    succ = TRANSITIONS.get(state, [])
    return succ[0] if succ else None
