#!/usr/bin/env python3
"""Regenerate LEARNING_LOG.md from the YAML frontmatter of every day note.

Usage:  python3 scripts/gen-learning-log.py   (run from the repo root)

Reads journal/month-NN/day-NNN.md, extracts day/date/week/time/confidence and
the H1 title, and writes a chronological, week-grouped index to LEARNING_LOG.md.
"""
import glob
import re

THEMES = {
    1: "Fundamentals",
    2: "Standard Library, Tooling & Testing",
    3: "Concurrency",
    4: "Web, REST & Databases",
    5: "gRPC & Architecture",
    6: "Production & Capstone",
}


def frontmatter(path):
    text = open(path, encoding="utf-8").read()
    block = re.search(r"^---\n(.*?)\n---", text, re.S)
    data = {}
    if block:
        for line in block.group(1).splitlines():
            kv = re.match(r"(\w+):\s*(.*)", line)
            if kv:
                data[kv.group(1)] = kv.group(2).strip().strip('"')
    h1 = re.search(r"^#\s+Day\s+\d+\s+[—-]\s+(.*)$", text, re.M)
    title = h1.group(1).strip() if h1 else data.get("topics", "")
    return data, title


def main():
    out = [
        "# 📓 Learning Log",
        "",
        "> One line per day — the chronological index of everything I've learned. "
        "Each entry links to its full day note in [`journal/`](journal/). "
        "Regenerate with `scripts/gen-learning-log.py`.",
        "",
        "**Format:** `Day NNN — date — topic — ⏱ min — 🎚 confidence/5 — [note](link)`",
        "",
    ]
    total = 0
    for mo in range(1, 7):
        files = sorted(glob.glob(f"journal/month-{mo:02d}/day-*.md"))
        if not files:
            continue
        out += [f"## Month {mo} — {THEMES[mo]}", ""]
        cur_week = None
        for f in files:
            data, title = frontmatter(f)
            wk = data.get("week", "?")
            if wk != cur_week:
                if cur_week is not None:
                    out.append("")  # close previous week's list
                out.append(f"**Week {wk}**")
                out.append("")  # blank line before the list (MD032)
                cur_week = wk
            out.append(
                f"- Day {data.get('day','?')} — {data.get('date','')} — {title} — "
                f"⏱ {data.get('time_spent_min','0')} — 🎚 {data.get('confidence','–')}/5 — [note]({f})"
            )
            total += 1
        out.append("")
    out += ["---", "", "⬅ [README](README.md) · [Progress](PROGRESS.md)"]
    open("LEARNING_LOG.md", "w", encoding="utf-8").write("\n".join(out) + "\n")
    print(f"wrote LEARNING_LOG.md: {total} days indexed")


if __name__ == "__main__":
    main()
