"""Small periodic summary for MCP-to-REST availability telemetry."""
from __future__ import annotations

import json
from collections import Counter
from pathlib import Path


path = Path("/data/mcp-audit.jsonl")
rows: list[dict] = []
malformed_rows = 0
if path.exists():
    for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
        try:
            row = json.loads(line)
        except json.JSONDecodeError:
            malformed_rows += 1
            continue
        if row.get("event") == "mcp_adapter_call":
            rows.append(row)
failures = [row for row in rows if row.get("error") or row.get("status") == "exception"]
availability = [row for row in failures if row.get("error") == "adapter_unavailable"]
print(json.dumps({
    "schema": "onec_mcp_audit_summary.v1", "status": "ok" if path.exists() else "log_not_found",
    "events": len(rows), "malformed_rows": malformed_rows,
    "bases": dict(Counter(str((row.get("request") or {}).get("base_id") or "<none>") for row in rows)),
    "failures": len(failures),
    "failure_methods": dict(Counter(str(row.get("method") or "<none>") for row in failures)),
    "recent_failures": failures[-20:],
    "findings": [
        *([{"priority": "P1", "kind": "rest_unavailable_from_mcp", "count": len(availability), "next_action": "Check MCP-to-REST connectivity, then find the same request_id in REST telemetry if it exists."}] if availability else []),
        *([{"priority": "P2", "kind": "malformed_audit_rows", "count": malformed_rows, "next_action": "Inspect proxy container restarts and log rotation."}] if malformed_rows else []),
    ],
}, ensure_ascii=False, indent=2))
