#!/usr/bin/env python3
"""Compute shares from reports.csv and write summary.json.

Usage: python3 summarise.py   (run from this directory or any other; paths are relative to this file)

Only rows with included == 1 are counted. Excluded/gated rows are reported separately.
Definitions live in methodology.md.
"""
import csv
import json
import statistics
from collections import Counter
from pathlib import Path

HERE = Path(__file__).resolve().parent
SECTIONS = [
    "sec_exec_summary", "sec_kpi_overview", "sec_rankings", "sec_backlinks",
    "sec_technical_issues", "sec_cwv_speed", "sec_onpage", "sec_content",
    "sec_local", "sec_conversions", "sec_competitors", "sec_work_done",
    "sec_recommendations_any", "sec_narrative", "sec_white_label",
]
# Sections that describe report *content areas* (used for the section count).
# White-label branding and narrative are properties, not content sections.
CONTENT_SECTIONS = [s for s in SECTIONS if s not in ("sec_white_label", "sec_narrative")]


def share(n, d):
    return {"n": n, "of": d, "share": round(n / d, 3) if d else None}


def main():
    rows = list(csv.DictReader(open(HERE / "reports.csv", encoding="utf-8")))
    inc = [r for r in rows if r["included"] == "1"]
    exc = [r for r in rows if r["included"] != "1"]
    n = len(inc)

    out = {
        "as_of": "2026-10-05",
        "rows_total": len(rows),
        "included": n,
        "excluded": len(exc),
        "excluded_reasons": {r["id"]: r["exclusion_reason"] for r in exc},
        "included_by_type": dict(Counter(r["type"] for r in inc)),
        "included_by_evidence_basis": dict(Counter(r["evidence_basis"] for r in inc)),
        "section_shares": {s: share(sum(r[s] == "1" for r in inc), n) for s in SECTIONS},
    }

    counts = [sum(r[s] == "1" for s in CONTENT_SECTIONS) for r in inc]
    out["content_section_count"] = {
        "definition": "number of the 13 content-area columns present (excludes narrative and white-label)",
        "median": statistics.median(counts),
        "mean": round(statistics.mean(counts), 2),
        "min": min(counts),
        "max": max(counts),
        "per_report": {r["id"]: c for r, c in zip(inc, counts)},
    }

    pa = Counter(r["prioritized_actions"] for r in inc)
    out["prioritized_actions"] = {
        "yes": share(pa["yes"], n),
        "partial": share(pa["partial"], n),
        "yes_or_partial": share(pa["yes"] + pa["partial"], n),
        "no": share(pa["no"], n),
        "ids_yes": [r["id"] for r in inc if r["prioritized_actions"] == "yes"],
        "ids_partial": [r["id"] for r in inc if r["prioritized_actions"] == "partial"],
    }
    out["concrete_next_tasks"] = share(sum(r["concrete_next_tasks"] == "1" for r in inc), n)
    out["any_recommendations_section"] = out["section_shares"]["sec_recommendations_any"]
    out["action_owner"] = share(sum(r["action_owner"] == "1" for r in inc), n)
    out["action_effort"] = share(sum(r["action_effort"] == "1" for r in inc), n)
    out["action_impact"] = share(sum(r["action_impact"] == "1" for r in inc), n)
    out["effort_or_impact_estimate"] = share(
        sum(r["action_effort"] == "1" or r["action_impact"] == "1" for r in inc), n)
    out["effort_and_impact_estimate"] = share(
        sum(r["action_effort"] == "1" and r["action_impact"] == "1" for r in inc), n)
    out["full_action_spec_owner_effort_impact_ranked"] = share(
        sum(r["prioritized_actions"] == "yes" and r["action_owner"] == "1"
            and r["action_effort"] == "1" and r["action_impact"] == "1" for r in inc), n)

    io = Counter(r["issues_ordered_by_priority"] for r in inc)
    with_issues = [r for r in inc if r["issues_ordered_by_priority"] != "na"]
    out["issues_ordered_by_priority"] = {
        "among_reports_with_issue_lists": len(with_issues),
        "yes": share(io["yes"], len(with_issues)),
        "partial": share(io["partial"], len(with_issues)),
        "no": share(io["no"], len(with_issues)),
    }

    items = [(r["id"], int(r["raw_items_count"])) for r in inc if r["raw_items_count"].strip()]
    audit_like = [(i, c) for i, c in items if any(
        k in next(r for r in inc if r["id"] == i)["raw_items_what"].lower()
        for k in ("issue", "check", "finding", "critical"))]
    out["raw_items"] = {
        "note": "counts are heterogeneous (issues, checks, widgets, keywords); see raw_items_what per row",
        "audit_like_reports": dict(audit_like),
        "audit_like_median": statistics.median([c for _, c in audit_like]) if audit_like else None,
    }

    # Data-hygiene: reports where a recommendation exists but no concrete task
    out["recommendations_without_concrete_tasks"] = [
        r["id"] for r in inc if r["sec_recommendations_any"] == "1" and r["concrete_next_tasks"] != "1"]
    out["by_type"] = {}
    for t in sorted(set(r["type"] for r in inc)):
        sub = [r for r in inc if r["type"] == t]
        out["by_type"][t] = {
            "n": len(sub),
            "prioritized_yes": sum(r["prioritized_actions"] == "yes" for r in sub),
            "recommendations_any": sum(r["sec_recommendations_any"] == "1" for r in sub),
            "work_done": sum(r["sec_work_done"] == "1" for r in sub),
        }
    full = [r for r in inc if r["evidence_basis"].startswith("full artifact") or r["evidence_basis"] == "live demo"]
    out["sensitivity_full_artifacts_and_live_demos_only"] = {
        "n": len(full),
        "prioritized_yes": share(sum(r["prioritized_actions"] == "yes" for r in full), len(full)),
        "recommendations_any": share(sum(r["sec_recommendations_any"] == "1" for r in full), len(full)),
        "effort_or_impact": share(sum(r["action_effort"] == "1" or r["action_impact"] == "1" for r in full), len(full)),
    }

    (HERE / "summary.json").write_text(json.dumps(out, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    print(json.dumps({k: out[k] for k in (
        "included", "prioritized_actions", "concrete_next_tasks", "any_recommendations_section",
        "effort_or_impact_estimate", "content_section_count")}, indent=1)[:3000])


if __name__ == "__main__":
    main()
