#!/usr/bin/env python3
"""Summarize rgltr audit logs."""

from __future__ import annotations

import argparse
import json
from collections import Counter
from pathlib import Path
from typing import Any, Iterable


def _iter_events(path: Path) -> Iterable[dict[str, Any]]:
    with path.open("r", encoding="utf-8") as handle:
        for line in handle:
            line = line.strip()
            if not line:
                continue
            try:
                yield json.loads(line)
            except json.JSONDecodeError:
                continue


def summarize(path: Path) -> None:
    all_events = list(_iter_events(path))
    runs: dict[str, list[dict[str, Any]]] = {}
    for event in all_events:
        run_id = event.get("run_id") or "unknown"
        runs.setdefault(run_id, []).append(event)

    print(f"runs: {len(runs)}")
    unknown_tools_total = 0
    unknown_tools_by_name: Counter[str] = Counter()

    for run_id, events in runs.items():
        context_ids = {event.get("context_id") for event in events if event.get("context_id")}
        context_label = ", ".join(sorted(context_ids)) if context_ids else "none"
        print(f"\nrun: {run_id} (context_id: {context_label})")
        turn_idx = 0
        current_turn: dict[str, Any] | None = None
        pending_unknown_calls: list[dict[str, Any]] = []

        for event in events:
            event_type = event.get("event_type")
            if event_type == "tool_call_unknown":
                tool_name = event.get("tool_name")
                if tool_name:
                    unknown_tools_total += 1
                    unknown_tools_by_name[tool_name] += 1
                    pending_unknown_calls.append(
                        {
                            "tool": tool_name,
                            "tool_call_id": event.get("tool_call_id"),
                            "unknown": True,
                        }
                    )

            if event_type == "tools_presented":
                turn_idx += 1
                current_turn = {
                    "active_tags_before": event.get("active_tags", []),
                    "visible_tools": event.get("payload", {}).get("tools", []),
                    "hidden_tools": [],
                    "tool_calls_requested": [],
                    "tool_calls_blocked": [],
                    "policy_decisions": [],
                    "rgltr_responses": [],
                }
                if pending_unknown_calls:
                    for call in pending_unknown_calls:
                        current_turn["tool_calls_requested"].append(call)
                        current_turn["tool_calls_blocked"].append(
                            {
                                "tool": call["tool"],
                                "decision": "unknown",
                            }
                        )
                    pending_unknown_calls = []
                print(f"  turn {turn_idx}:")
                print(f"    active_tags_before: {current_turn['active_tags_before']}")
                print(f"    visible_tools: {current_turn['visible_tools']}")
                continue

            if current_turn is None:
                continue

            tool_name = event.get("tool_name")
            if event_type == "tool_hidden" and tool_name:
                current_turn["hidden_tools"].append(
                    {
                        "tool": tool_name,
                        "reason": event.get("reason"),
                    }
                )
            elif event_type == "tool_call_requested" and tool_name:
                current_turn["tool_calls_requested"].append(
                    {
                        "tool": tool_name,
                        "tool_call_id": event.get("tool_call_id"),
                    }
                )
                if tool_name not in current_turn["visible_tools"]:
                    unknown_tools_total += 1
                    unknown_tools_by_name[tool_name] += 1
            elif event_type == "policy_decision" and tool_name:
                current_turn["policy_decisions"].append(
                    {
                        "tool": tool_name,
                        "decision": event.get("decision"),
                        "reason": event.get("policy_reason"),
                        "enforced": event.get("enforced"),
                    }
                )
                if event.get("decision") in {"deny", "approval"}:
                    current_turn["tool_calls_blocked"].append(
                        {
                            "tool": tool_name,
                            "decision": event.get("decision"),
                        }
                    )
            elif event_type == "tool_allowed" and tool_name:
                current_turn["rgltr_responses"].append(
                    {
                        "tool": tool_name,
                        "active_tags_after": event.get("active_tags_after"),
                        "would_block": event.get("would_block"),
                        "would_require_approval": event.get("would_require_approval"),
                    }
                )

        if current_turn is not None and pending_unknown_calls:
            for call in pending_unknown_calls:
                current_turn["tool_calls_requested"].append(call)
                current_turn["tool_calls_blocked"].append(
                    {
                        "tool": call["tool"],
                        "decision": "unknown",
                    }
                )
            pending_unknown_calls = []

        if current_turn is not None:
            print(f"    hidden_tools: {current_turn['hidden_tools']}")
            print(f"    tool_calls_requested: {current_turn['tool_calls_requested']}")
            print(f"    tool_calls_blocked: {current_turn['tool_calls_blocked']}")
            print(f"    policy_decisions: {current_turn['policy_decisions']}")
            print(f"    rgltr_responses: {current_turn['rgltr_responses']}")

    print("\nunknown_tool_calls:")
    print(f"  total: {unknown_tools_total}")
    for name, count in unknown_tools_by_name.most_common():
        if count:
            print(f"  {name}: {count}")


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Summarize rgltr audit logs.")
    parser.add_argument("path", type=Path)
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    summarize(args.path)


if __name__ == "__main__":
    main()
