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

import csv
import re
from collections import defaultdict
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
STATUS_MATRIX = ROOT / "artifacts" / "status-matrix.csv"
GAP_ANALYSIS = ROOT / "artifacts" / "gap-analysis.md"
START_MARKER = "<!-- status-summary:start -->"
END_MARKER = "<!-- status-summary:end -->"

STATUS_RU = {
    "closed": "ЗАКРЫТО",
    "partial": "ЧАСТИЧНО",
    "open": "ОТКРЫТО",
    "blocked": "ЗАБЛОКИРОВАНО",
}

STATUS_EN = {
    "closed": "CLOSED",
    "partial": "PARTIAL",
    "open": "OPEN",
    "blocked": "BLOCKED",
}


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


def format_gaps(rows: list[dict[str, str]]) -> str:
    parent_titles = {row["scope_id"]: row["title"] for row in rows}

    phases = [row for row in rows if row["scope_type"] == "phase"]
    categories = [row for row in rows if row["scope_type"] == "category"]
    gaps = [row for row in rows if row["scope_type"] == "gap"]

    phase_gaps: dict[str, list[str]] = defaultdict(list)
    category_gaps: dict[str, list[str]] = defaultdict(list)
    for gap in gaps:
        parent = gap["parent_scope"]
        if parent.startswith("PH"):
            phase_gaps[parent].append(gap["scope_id"])
        elif parent.startswith("EC"):
            category_gaps[parent].append(gap["scope_id"])

    lines: list[str] = []
    lines.append(START_MARKER)
    lines.append("")
    lines.append("### По фазам методологии")
    lines.append("")
    lines.append("| Фаза | Статус | Canonical gaps |")
    lines.append("|------|--------|----------------|")
    for row in phases:
        gaps_text = ", ".join(phase_gaps.get(row["scope_id"], [])) or "—"
        lines.append(f"| {row['title']} | {STATUS_RU[row['status']]} | {gaps_text} |")

    lines.append("")
    lines.append("### По категориям экспозиции")
    lines.append("")
    lines.append("| Категория | Статус | Canonical gaps |")
    lines.append("|-----------|--------|----------------|")
    for row in categories:
        gaps_text = ", ".join(category_gaps.get(row["scope_id"], [])) or "—"
        lines.append(f"| {row['title']} | {STATUS_RU[row['status']]} | {gaps_text} |")

    lines.append("")
    lines.append("### Открытые и заблокированные пробелы")
    lines.append("")
    lines.append("| Scope | ID | Статус | Приоритет | Blocker / Summary |")
    lines.append("|-------|----|--------|-----------|-------------------|")
    for row in gaps:
        status = STATUS_EN[row["status"]]
        blocker = row["blocked_reason"] or row["title"]
        scope = parent_titles.get(row["parent_scope"], row["parent_scope"])
        lines.append(f"| {scope} | {row['scope_id']} | {status} | {row['priority'].upper()} | {blocker} |")

    lines.append("")
    lines.append(END_MARKER)
    return "\n".join(lines)


def rewrite_gap_analysis(block: str) -> None:
    text = GAP_ANALYSIS.read_text()
    pattern = re.compile(
        re.escape(START_MARKER) + r".*?" + re.escape(END_MARKER),
        re.DOTALL,
    )
    replaced, count = pattern.subn(block, text)
    if count != 1:
        raise RuntimeError("managed status summary block not found or duplicated in gap-analysis.md")
    GAP_ANALYSIS.write_text(replaced)


def main() -> int:
    rows = load_rows()
    block = format_gaps(rows)
    rewrite_gap_analysis(block)
    print(f"updated status summary block from {STATUS_MATRIX}")
    return 0


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