#!/usr/bin/env python3
from __future__ import annotations

import csv
from collections import Counter, defaultdict
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
STATUS_MATRIX = ROOT / "artifacts" / "status-matrix.csv"


def load_rows() -> list[dict[str, str]]:
    with STATUS_MATRIX.open(newline="") as handle:
        return list(csv.DictReader(handle))


def print_section(title: str) -> None:
    print(title)


def main() -> int:
    rows = load_rows()
    by_type: dict[str, list[dict[str, str]]] = defaultdict(list)
    for row in rows:
        by_type[row["scope_type"]].append(row)

    overall = Counter(row["status"] for row in rows)
    print_section("Overall")
    print(
        f"closed={overall['closed']} partial={overall['partial']} "
        f"open={overall['open']} blocked={overall['blocked']}"
    )
    print()

    for scope_type in ["phase", "category", "artifact", "dataset", "gap"]:
        scoped = by_type.get(scope_type, [])
        counts = Counter(row["status"] for row in scoped)
        print_section(scope_type)
        print(
            f"total={len(scoped)} closed={counts['closed']} partial={counts['partial']} "
            f"open={counts['open']} blocked={counts['blocked']}"
        )
        if scope_type == "gap":
            print("high-signal gaps:")
            for row in scoped:
                if row["status"] in {"open", "blocked"} and row["priority"] in {"high", "critical"}:
                    blocker = f" blocker={row['blocked_reason']}" if row["blocked_reason"] else ""
                    print(f"- {row['scope_id']} {row['status']} priority={row['priority']}{blocker} :: {row['title']}")
        print()

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
