#!/usr/bin/env python3
"""Build a tiny HTML index from Markdown notes in the learning log."""

from __future__ import annotations

import html
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
OUTPUT = ROOT / "learning-log.html"


def main() -> None:
    notes = sorted(
        path for path in ROOT.glob("*.md") if path.name.lower() != "readme.md"
    )
    items = []
    for path in notes:
        text = path.read_text(encoding="utf-8").strip()
        title = path.stem.replace("-", " ").title()
        if text.startswith("# "):
            title = text.splitlines()[0].removeprefix("# ").strip()
        items.append(
            f"<article><h2>{html.escape(title)}</h2>"
            f"<pre>{html.escape(text)}</pre></article>"
        )

    body = "\n".join(items) or "<p>No learning notes yet.</p>"
    OUTPUT.write_text(
        "<!doctype html><html lang='en'><meta charset='utf-8'>"
        "<meta name='viewport' content='width=device-width, initial-scale=1'>"
        "<title>Learning Log</title>"
        "<style>body{font-family:system-ui,sans-serif;line-height:1.5;max-width:900px;margin:40px auto;padding:0 20px}"
        "article{border-top:1px solid #ddd;padding:20px 0}pre{white-space:pre-wrap;background:#f7f7f7;padding:16px;border-radius:8px}</style>"
        "<h1>Learning Log</h1>"
        f"{body}</html>",
        encoding="utf-8",
    )
    print(OUTPUT)


if __name__ == "__main__":
    main()
