"""Read relay outbox reports from state/relay/outbox/{category}/*.json."""

from __future__ import annotations

import json
import logging
from pathlib import Path

logger = logging.getLogger(__name__)

# Project root: src/vastian/relay/reader.py -> parents[3]
_PROJECT_ROOT = Path(__file__).resolve().parents[3]
RELAY_OUTBOX_ROOT = _PROJECT_ROOT / "state" / "relay" / "outbox"

# Expected keys in each report JSON (schema)
RELAY_REPORT_KEYS = ("agent_id", "category", "summary", "payload", "timestamp")


def read_relay_outbox(project_root: Path | None = None) -> list[dict]:
    """Read all relay report JSON files from state/relay/outbox/{category}/.

    Returns a list of report dicts, each with at least:
      - agent_id, category, summary
      - payload (dict, optional), timestamp (str, optional)
      - _source_file, _category (from path)

    Categories: ux, prompts, ops, pulse, personas, metrics, scenarios, knowledge, config.
    """
    root = project_root or _PROJECT_ROOT
    outbox = root / "state" / "relay" / "outbox"
    if not outbox.exists():
        return []

    reports: list[dict] = []
    for category_dir in sorted(outbox.iterdir()):
        if not category_dir.is_dir() or category_dir.name.startswith("."):
            continue
        category = category_dir.name
        for path in sorted(category_dir.glob("*.json")):
            if path.name.startswith("."):
                continue
            try:
                data = json.loads(path.read_text(encoding="utf-8"))
                if not isinstance(data, dict):
                    continue
                data["_source_file"] = path.name
                data["_category"] = category
                data.setdefault("agent_id", "")
                data.setdefault("category", category)
                data.setdefault("summary", "")
                data.setdefault("payload", {})
                reports.append(data)
            except (json.JSONDecodeError, OSError) as e:
                logger.warning("Skipping relay outbox file %s: %s", path, e)
    return reports
