"""
Genesis Persistent Context Architecture — Interceptors Package
Story 1.03 — Track B

Exports:
  BaseInterceptor, InterceptorMetadata — abstract base + metadata dataclass
  InterceptorChain                     — ordered execution engine
  GLOBAL_CHAIN                         — module-level singleton chain
  register_interceptor()               — convenience helper to add to GLOBAL_CHAIN
  dispatch_to_swarm()                  — central dispatch function
"""
import uuid
from datetime import datetime, timezone
from typing import Optional

from .base_interceptor import BaseInterceptor, InterceptorMetadata
from .interceptor_chain import InterceptorChain

# ---------------------------------------------------------------------------
# Module-level singleton chain — shared across the process lifetime
# ---------------------------------------------------------------------------
GLOBAL_CHAIN = InterceptorChain()


def register_interceptor(interceptor: BaseInterceptor) -> None:
    """Convenience helper: add an interceptor to the process-global chain."""
    GLOBAL_CHAIN.register(interceptor)


async def dispatch_to_swarm(
    task_payload: dict,
    tier: Optional[str] = None,
    context: Optional[dict] = None,
) -> dict:
    """Central dispatch function.

    Assigns a UUID4 task_id if one is not already present, stamps
    ``dispatched_at`` in UTC ISO-8601, optionally tags the payload with
    ``tier``, then runs the interceptor chain pre/post hooks around the
    internal task executor.

    Returns a result dict that always includes ``task_id`` and ``status``.
    On success: ``{"status": "completed", "task_id": ..., ...}``
    On error:   ``{"status": "error",     "task_id": ..., "correction": ...}``
    """
    # --- Stamp task_id and dispatch time ----------------------------------------
    if "task_id" not in task_payload:
        task_payload["task_id"] = str(uuid.uuid4())
    task_payload["dispatched_at"] = datetime.now(timezone.utc).isoformat()
    if tier is not None:
        task_payload["tier"] = tier

    task_id = task_payload["task_id"]

    try:
        enriched = await GLOBAL_CHAIN.execute_pre(task_payload)
        result = await _execute_task(enriched)
        await GLOBAL_CHAIN.execute_post(result, enriched)
        return {**result, "task_id": task_id, "status": "completed"}
    except Exception as exc:  # noqa: BLE001
        correction = await GLOBAL_CHAIN.execute_error(exc, task_payload)
        return {"task_id": task_id, "status": "error", "correction": correction}


async def _execute_task(task_payload: dict) -> dict:
    """Stub executor — passthrough until real Gemini/Opus dispatch is wired in.

    Returns the prompt text (if present) as ``output``.  Will be replaced by
    the real execution layer in a later story.
    """
    return {
        "task_id": task_payload.get("task_id", "unknown"),
        "output": task_payload.get("prompt", ""),
        "status": "completed",
    }


# VERIFICATION_STAMP
# Story: 1.03 (Track B)
# Verified By: parallel-builder
# Verified At: 2026-02-25T00:00:00Z
# Tests: 7/7
# Coverage: 100%
