#!/usr/bin/env python3
"""Regenerate the dynamic README badges and the content-stats table from the
file tree, so they never drift from reality.

Usage:  python3 scripts/gen-badges.py        # run from the repo root
        python3 scripts/gen-badges.py --check # exit 1 if README is stale (CI)

It rewrites only the regions delimited by:
    <!-- BADGES:START ... --> ... <!-- BADGES:END -->
    <!-- CONTENT-STATS:START ... --> ... <!-- CONTENT-STATS:END -->
Everything else in README.md is left untouched.
"""
import glob
import os
import re
import sys

README = "README.md"
PROJECT_TOTAL = 7  # planned number of projects (projects/01..07)


def counts():
    day_notes = len(glob.glob("journal/month-*/day-*.md"))
    week_reviews = len(glob.glob("journal/month-*/week-*-review.md"))
    month_reviews = len(glob.glob("journal/month-*/month-*-review.md"))
    months = len([d for d in glob.glob("journal/month-*") if os.path.isdir(d)
                  and glob.glob(os.path.join(d, "day-*.md"))])
    examples = len(glob.glob("examples/**/main.go", recursive=True))
    exercise_dirs = {os.path.dirname(p)
                     for p in glob.glob("exercises/**/*_test.go", recursive=True)}
    projects_impl = len([d for d in glob.glob("projects/0*")
                         if glob.glob(os.path.join(d, "**/*.go"), recursive=True)])
    interview_files = [f for f in glob.glob("interview/*.md")
                       if os.path.basename(f).lower() != "readme.md"]
    qs = sum(open(f, encoding="utf-8").read().count("<details>") for f in interview_files)
    cheats = len([f for f in glob.glob("cheatsheets/*.md")
                  if os.path.basename(f).lower() != "readme.md"])
    return {
        "day_notes": day_notes, "week_reviews": week_reviews,
        "month_reviews": month_reviews, "months": months, "examples": examples,
        "exercises": len(exercise_dirs), "projects_impl": projects_impl,
        "interview_files": len(interview_files), "qs": qs, "cheats": cheats,
    }


def badge(label, message, color):
    enc = lambda s: str(s).replace("-", "--").replace(" ", "_").replace("/", "%2F").replace("+", "%2B")
    return f"![{label}](https://img.shields.io/badge/{enc(label)}-{enc(message)}-{color})"


def badges_block(c):
    qs_round = (c["qs"] // 10) * 10
    lines = [
        badge("Curriculum", f"{c['months']} months authored", "success"),
        badge("day notes", c["day_notes"], "blue"),
        badge("projects", f"{c['projects_impl']}/{PROJECT_TOTAL}", "blue"),
        badge("examples", c["examples"], "blue"),
        badge("exercises", c["exercises"], "blue"),
        badge("interview Qs", f"{qs_round}+", "blue"),
        badge("cheatsheets", c["cheats"], "blue"),
    ]
    return "\n".join(lines)


def stats_table(c):
    qs_round = (c["qs"] // 10) * 10
    rows = [
        "| Metric | Value |",
        "|---|---|",
        f"| Curriculum authored | ✅ {c['months']} months · {c['day_notes']} day notes · "
        f"{c['week_reviews']} weekly + {c['month_reviews']} monthly reviews |",
        f"| Projects implemented | ✅ {c['projects_impl']} / {PROJECT_TOTAL} (beginner → production capstone) |",
        f"| Runnable examples | {c['examples']} (stdlib-only) |",
        f"| Exercises (with tests) | {c['exercises']} |",
        f"| Interview questions | {qs_round}+ across {c['interview_files']} files |",
        f"| Cheatsheets | {c['cheats']} |",
    ]
    return "\n".join(rows)


def replace_region(text, name, body):
    pat = re.compile(rf"(<!-- {name}:START[^>]*-->\n).*?(\n<!-- {name}:END -->)", re.S)
    if not pat.search(text):
        sys.exit(f"error: {name} markers not found in {README}")
    return pat.sub(lambda m: m.group(1) + body + m.group(2), text)


def main():
    check = "--check" in sys.argv
    c = counts()
    original = open(README, encoding="utf-8").read()
    updated = replace_region(original, "BADGES", badges_block(c))
    updated = replace_region(updated, "CONTENT-STATS", stats_table(c))
    if check:
        if updated != original:
            sys.exit("README badges/stats are stale — run: python3 scripts/gen-badges.py")
        print("README badges/stats are up to date.")
        return
    open(README, "w", encoding="utf-8").write(updated)
    print("Updated README badges + content stats:",
          ", ".join(f"{k}={v}" for k, v in c.items()))


if __name__ == "__main__":
    main()
