"""Write relay report JSON files to state/relay/outbox/{category}/."""

from __future__ import annotations

import json
import logging
from datetime import UTC, datetime
from pathlib import Path

logger = logging.getLogger(__name__)

_PROJECT_ROOT = Path(__file__).resolve().parents[3]
RELAY_CATEGORIES = frozenset(
    {
        "ux",
        "prompts",
        "ops",
        "pulse",
        "personas",
        "metrics",
        "scenarios",
        "knowledge",
        "config",  # L7: config change suggestions (Theo, Orion, Henry) -> Maria -> session cards
    }
)


def write_relay_report(
    agent_id: str,
    category: str,
    summary: str,
    payload: dict | None = None,
    project_root: Path | None = None,
) -> str | None:
    """Write a relay report to state/relay/outbox/{category}/.

    Returns the relative path of the written file, or None on error.
    """
    root = project_root or _PROJECT_ROOT
    if category not in RELAY_CATEGORIES:
        logger.warning("Relay category %r not in %s", category, sorted(RELAY_CATEGORIES))
        return None
    outbox_dir = root / "state" / "relay" / "outbox" / category
    outbox_dir.mkdir(parents=True, exist_ok=True)
    ts = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
    safe_agent = agent_id.replace("/", "-").replace("\\", "-")[:32]
    filename = f"{safe_agent}_{ts}.json"
    path = outbox_dir / filename
    data = {
        "agent_id": agent_id,
        "category": category,
        "summary": summary[:2000],
        "payload": payload or {},
        "timestamp": datetime.now(UTC).isoformat(),
    }
    try:
        path.write_text(json.dumps(data, indent=2, default=str), encoding="utf-8")
        return str(path.relative_to(root)).replace("\\", "/")
    except (OSError, ValueError) as e:
        logger.warning("Failed to write relay report %s: %s", path, e)
        return None
