#!/usr/bin/env python3
"""Engram recall-log metrics — parse and summarise success rates."""

from __future__ import annotations

import re
import sys
from collections import defaultdict
from pathlib import Path


def main() -> None:
    log = Path.home() / "recall.log"

    if not log.exists():
        print("No log found at", log)
        sys.exit(1)

    content = log.read_text()

    # Format: [2026-03-28T12:00:00] [model] [domain/sub] [SUCCESS] command...
    entries = re.findall(
        r"\[(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})\] \[(\w+)\] \[(\w+/\w+)\] \[(\w+)\](.*)",
        content,
        re.M,
    )

    metrics: dict[str, dict[str, dict[str, int]]] = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))

    for _date, model, category, status, _cmd in entries:
        metrics[model][category][status] += 1

    print("| Model | Category | Success % | Runs |")
    print("|-------|----------|-----------|------|")
    for model, cats in metrics.items():
        for cat, stats in cats.items():
            total = stats["SUCCESS"] + stats["FAILURE"]
            rate = (stats["SUCCESS"] / total * 100) if total else 0
            print(f"| {model} | {cat} | {rate:.1f}% | {total} |")


if __name__ == "__main__":
    main()
