#!/usr/bin/env python3
"""Generate one Brain-Note per top-N Maven lesson with full chapter list +
implementation ideas. Output to /root/aria/brain/02-Wissen/maven-lessons/.
"""
from __future__ import annotations

import json
import re
from datetime import datetime
from pathlib import Path

CLASSIFIED = Path("/root/aria/state/maven/lessons-classified.jsonl")
RAW_DIR = Path("/root/aria/state/maven/lessons-raw")
OUT_DIR = Path("/root/aria/brain/02-Wissen/maven-lessons")
TOP_N = 100


def load_rows():
    rows = []
    for line in CLASSIFIED.read_text().splitlines():
        if not line.strip():
            continue
        try:
            rows.append(json.loads(line))
        except json.JSONDecodeError:
            pass
    return rows


def slug_filename(slug: str) -> str:
    return re.sub(r"[^a-zA-Z0-9._-]", "-", slug)[:120]


def raw_path_for(url: str) -> Path:
    parts = url.rstrip("/").split("/")
    fname = f"{parts[-2]}--{parts[-1]}.json"
    return RAW_DIR / fname


def render_chapters(chapters: list) -> str:
    if not chapters:
        return "_keine Chapter\\-Daten_"
    lines = []
    for c in chapters:
        secs = int(c.get("start_seconds", 0))
        mm = secs // 60
        ss = secs % 60
        title = (c.get("title") or "").strip()
        lines.append(f"- **{mm:02d}:{ss:02d}** — {title}")
    return "\n".join(lines)


def render_one(row: dict) -> str:
    url = row["url"]
    raw_path = raw_path_for(url)
    chapters = []
    extra = {}
    if raw_path.exists():
        try:
            data = json.loads(raw_path.read_text())
            pp = data.get("next_data", {}).get("props", {}).get("pageProps", {})
            chapters = pp.get("videoChapters") or []
            cp = pp.get("contentPage") or {}
            section = (cp.get("sections") or [{}])[0]
            extra["bio_html"] = (section.get("instructor_infos") or [{}])[0].get("bio_html", "")
            extra["learning_outcomes"] = section.get("learning_outcomes") or []
            extra["topic_desc"] = section.get("topic_desc") or ""
        except Exception:
            pass

    title = row.get("title") or "(ohne Titel)"
    fm = [
        "---",
        f"title: {title}",
        "type: reference",
        "tags: [maven, " + ", ".join(t.lower().replace('/', '-') for t in (row.get('tags') or [])) + "]",
        f"date: 2026-05-20",
        f"source: {url}",
        f"speaker: {row.get('instructor_name') or '?'}",
        f"school: {row.get('school_name') or '?'}",
        f"duration_min: {row.get('duration_min')}",
        f"start_datetime: {row.get('start_datetime')}",
        f"chapter_count: {len(chapters)}",
        f"aria_score: {row.get('aria_score', 0)}",
        f"matched_keywords: {row.get('aria_matched_keywords', [])}",
        "---",
        "",
        f"# {title}",
        "",
        f"**Quelle:** {url}",
        "",
        f"- Speaker: **{row.get('instructor_name') or '?'}** · {row.get('instructor_headline') or row.get('instructor_title') or ''}",
        f"- Schule: {row.get('school_name')}",
        f"- Dauer: {row.get('duration_min')} min · {row.get('start_datetime') or '?'}",
        f"- Tags: {', '.join(row.get('tags') or [])}",
        f"- Aria-Score: **{row.get('aria_score', 0)}** (Keywords: {', '.join(row.get('aria_matched_keywords') or [])})",
        "",
    ]

    if extra.get("topic_desc"):
        fm.extend(["## Beschreibung", "", extra["topic_desc"], ""])

    if extra.get("learning_outcomes"):
        fm.extend(["## Lernziele", ""])
        for lo in extra["learning_outcomes"]:
            txt = lo.get("text") if isinstance(lo, dict) else str(lo)
            if txt:
                fm.append(f"- {txt}")
        fm.append("")

    fm.extend(["## Chapters", "", render_chapters(chapters), ""])

    if extra.get("bio_html"):
        bio = re.sub(r"<[^>]+>", "", extra["bio_html"]).strip()
        if bio:
            fm.extend(["## Speaker-Bio", "", bio[:1500], ""])

    # Aria/Kadi-Hebel placeholder (auto-derived from tags)
    tags = set(row.get("tags") or [])
    levers = []
    if "AI/Agents" in tags:
        levers.append("- Pattern für Aria-Agent-Architektur (Multi-Agent / Tool-Calls / Memory)")
    if "AI/Tooling" in tags:
        levers.append("- Tooling-Workflows die in Aria-Skills oder Kadi-Modulen reused werden können")
    if "Engineering/Observability" in tags:
        levers.append("- Eval-/Trace-Patterns für Aria-Skill-Quality + Kadi-PRs")
    if "Product" in tags or "Product/Strategy" in tags:
        levers.append("- PM-Frameworks für Kadi-Roadmap, BMW-Lieferant-Use-Cases")
    if "Leadership/Management" in tags:
        levers.append("- Team-/Workshop-Patterns für PMO-Cockpit (KAR-343)")
    if "Marketing" in tags:
        levers.append("- Content/Distribution für Aria-Spec-Selling")
    if not levers:
        levers.append("- Allgemeiner Lern-Kontext, kein direkter Aria/Kadi-Hebel sichtbar")
    fm.extend(["## Aria/Kadi-Hebel (Hypothesen)", ""] + levers + [""])

    fm.extend([
        "## Status",
        "",
        "- Metadaten gecrawlt: ✓",
        "- Transcript: _offen — Maven blockt Headless-Download. Phase 2: YouTube-Cross-Reference oder Cookies._",
        "- Implementation-KAR: _siehe Aria-Master-Note für Aggregat-KARs_",
        "",
    ])
    return "\n".join(fm)


def main():
    rows = load_rows()
    rows.sort(key=lambda r: r.get("aria_score", 0), reverse=True)
    top = rows[:TOP_N]
    print(f"# top {len(top)} lessons by aria_score (min={top[-1].get('aria_score',0)}, max={top[0].get('aria_score',0)})")

    OUT_DIR.mkdir(parents=True, exist_ok=True)
    written = 0
    for r in top:
        slug = r.get("slug") or "no-slug"
        title_slug = re.sub(r"[^a-zA-Z0-9-]", "-", (r.get("title") or "no-title").lower())[:80]
        fname = f"{slug}--{title_slug}.md"
        path = OUT_DIR / slug_filename(fname)
        path.write_text(render_one(r))
        written += 1
    print(f"wrote {written} files into {OUT_DIR}")


if __name__ == "__main__":
    main()
