"""Lesson store — load curated lesson specs + generated lesson content.

Specs (curated, hand-written) live in lessons/specs.json.
Generated content (phrases + dialogue, authored by Claude via gen_lessons.py)
is cached per-lesson in lessons/data/<id>.json.

The app reads through here; it never calls Claude to author lessons at request
time (that's gen_lessons.py's job, run offline).
"""
import json
from pathlib import Path

ROOT = Path(__file__).parent
SPECS_PATH = ROOT / "lessons" / "specs.json"
DATA_DIR = ROOT / "lessons" / "data"


def load_specs() -> list:
    """Curated lesson specs (id, title, level, summary, prompt), in order."""
    return json.loads(SPECS_PATH.read_text())


def load_index() -> list:
    """Lesson list for the library view. Marks which lessons have generated
    content ready (`ready`) and how many phrases they hold (`count`)."""
    index = []
    for spec in load_specs():
        data_path = DATA_DIR / f"{spec['id']}.json"
        ready = data_path.exists()
        count = 0
        if ready:
            count = len(json.loads(data_path.read_text()).get("items", []))
        index.append({
            "id": spec["id"],
            "title": spec["title"],
            "level": spec["level"],
            "summary": spec["summary"],
            "ready": ready,
            "count": count,
        })
    return index


def load_lesson(lesson_id: str) -> dict | None:
    """Full lesson: spec metadata merged with generated items + dialogue.
    Returns None if the id is unknown. Raises if the id is known but content
    hasn't been generated yet (fail loud — run gen_lessons.py)."""
    spec = next((s for s in load_specs() if s["id"] == lesson_id), None)
    if spec is None:
        return None
    data_path = DATA_DIR / f"{lesson_id}.json"
    content = json.loads(data_path.read_text())  # raises if not generated yet
    return {
        "id": spec["id"],
        "title": spec["title"],
        "level": spec["level"],
        "summary": spec["summary"],
        "items": content.get("items", []),
        "dialogue": content.get("dialogue", []),
    }
