"""Component registry.

A component declares the state it handles and a handler. The router never
imports a component by name — it asks the registry "who handles state X?".
Registering a new component is therefore a one-liner and requires no edit to
the router.

Three kinds of component
------------------------
``state``   (default) routable: exactly one per pipeline state. Reached by
            ``service.advance()`` via ``get_for_state()``.
``intake``  runs once at job creation, enriches the job at its initial state.
            Reached via ``get_intake()``.
``tool``    a registered, discoverable capability that is NOT a pipeline state
            (e.g. the opportunity engine). It has no ``handles_state`` and is
            never routed to by the state machine; callers look it up by name
            through the registry (``get_tool``) instead of importing the module.
            This keeps "who does what" in one place without inventing new
            pipeline states.

Handler contract
----------------
    handler(job: dict) -> dict

The returned dict must contain:
    to_state       : str   the state the job moves to (validated by the state machine)
    note           : str   what the component actually did (goes into the audit log)
    payload_patch  : dict  optional top-level merge into the job payload
    data           : dict  optional structured output, stored on the event row

Tool components return ``to_state: None`` — they are not transitions.
"""

from __future__ import annotations

from typing import Callable

from .errors import NoComponent, RegistryError
from .state_machine import ALL_STATES

KIND_STATE = "state"
KIND_INTAKE = "intake"
KIND_TOOL = "tool"
KINDS = (KIND_STATE, KIND_INTAKE, KIND_TOOL)


class Component:
    def __init__(
        self,
        name: str,
        handles_state: str | None,
        handler: Callable[[dict], dict],
        description: str = "",
        intake: bool = False,
        produces_state: str | None = None,
        kind: str | None = None,
    ):
        if not name:
            raise RegistryError("component name is required")
        if kind is None:
            kind = KIND_INTAKE if intake else KIND_STATE
        if kind not in KINDS:
            raise RegistryError(f"component {name!r} declares unknown kind {kind!r}")
        if kind == KIND_TOOL:
            if intake:
                raise RegistryError(f"tool component {name!r} cannot be an intake component")
            if handles_state is not None and handles_state not in ALL_STATES:
                raise RegistryError(
                    f"component {name!r} declares unknown handles_state {handles_state!r}"
                )
        else:
            if handles_state not in ALL_STATES:
                raise RegistryError(
                    f"component {name!r} declares unknown handles_state {handles_state!r}"
                )
        if not callable(handler):
            raise RegistryError(f"component {name!r} handler is not callable")
        self.name = name
        self.handles_state = handles_state
        self.handler = handler
        self.description = description
        self.intake = kind == KIND_INTAKE
        self.kind = kind
        self.produces_state = produces_state

    def describe(self) -> dict:
        return {
            "name": self.name,
            "handles_state": self.handles_state,
            "produces_state": self.produces_state,
            "intake": self.intake,
            "kind": self.kind,
            "description": self.description,
        }

    def __repr__(self) -> str:  # pragma: no cover - debug helper
        return f"<Component {self.name} kind={self.kind} handles={self.handles_state}>"


class Registry:
    """state -> component. One routable component per state, plus intake and tools."""

    def __init__(self) -> None:
        self._routable: dict[str, Component] = {}
        self._intake: dict[str, Component] = {}
        self._tools: dict[str, Component] = {}
        self._by_name: dict[str, Component] = {}

    # -- registration ------------------------------------------------------
    def register(self, component: Component) -> Component:
        if component.name in self._by_name:
            raise RegistryError(f"a component named {component.name!r} is already registered")
        if component.kind == KIND_TOOL:
            self._tools[component.name] = component
            self._by_name[component.name] = component
            return component
        bucket = self._intake if component.intake else self._routable
        if component.handles_state in bucket:
            other = bucket[component.handles_state]
            raise RegistryError(
                f"state {component.handles_state!r} is already handled by {other.name!r}"
            )
        bucket[component.handles_state] = component
        self._by_name[component.name] = component
        return component

    def unregister(self, name: str) -> None:
        comp = self._by_name.pop(name, None)
        if comp is None:
            raise RegistryError(f"no component named {name!r}")
        if comp.kind == KIND_TOOL:
            self._tools.pop(comp.name, None)
            return
        bucket = self._intake if comp.intake else self._routable
        bucket.pop(comp.handles_state, None)

    def has(self, name: str) -> bool:
        return name in self._by_name

    # -- lookup ------------------------------------------------------------
    def get_for_state(self, state: str) -> Component:
        comp = self._routable.get(state)
        if comp is None:
            raise NoComponent(
                f"no component registered to handle state {state!r}; "
                f"registered states: {sorted(self._routable) or 'none'}"
            )
        return comp

    def get_intake(self, state: str) -> Component | None:
        return self._intake.get(state)

    def get(self, name: str) -> Component | None:
        return self._by_name.get(name)

    def get_tool(self, name: str) -> Component:
        comp = self._tools.get(name)
        if comp is None:
            raise NoComponent(
                f"no tool component named {name!r}; registered tools: "
                f"{sorted(self._tools) or 'none'}"
            )
        return comp

    def routable(self) -> dict[str, Component]:
        return dict(self._routable)

    def tools(self) -> dict[str, Component]:
        return dict(self._tools)

    def all(self) -> list[Component]:
        return list(self._by_name.values())

    def describe(self) -> list[dict]:
        return [c.describe() for c in self.all()]

    def clear(self) -> None:
        self._routable.clear()
        self._intake.clear()
        self._tools.clear()
        self._by_name.clear()


#: The process-wide registry the app and CLI use.
REGISTRY = Registry()
