#!/usr/bin/env python3
"""
Render ELA weeks 24-32 JSON outlines to PDFs.

Usage:
    python3 render_weeks_24_32.py [--weeks 24,25] [--dry]

Renders all JSON files in outlines/ using the shared render engine.
Output goes to Week_XX/Day/ subdirectories (matching existing structure).
"""

import sys
import os
from pathlib import Path

# Add shared engine to path
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "shared"))
from render import render_outline

BASE_DIR = Path(__file__).parent
OUTLINES_DIR = BASE_DIR / "outlines"
TEMPLATE_DIR = BASE_DIR / "templates"

# Map day names to output subdirs (matching existing Week structure)
DAY_SUBDIRS = {
    "Monday": "Monday",
    "Tuesday": "Tuesday",
    "Wednesday": "Wednesday",
    "Thursday": "Thursday",
    "Friday": "Friday",
}

def render_week_weekly(outline_path, verbose=True):
    """Render a single outline JSON to the correct Week_NN/Day/ structure."""
    import json

    with open(outline_path) as f:
        outline = json.load(f)

    week = outline.get("week", 0)
    day = outline.get("day", "Unknown")

    # Output: Week_24/Monday/
    output_subdir = BASE_DIR / f"Week_{week}" / DAY_SUBDIRS.get(day, day)

    pdf_path = render_outline(
        outline_path=str(outline_path),
        template_dir=str(TEMPLATE_DIR),
        output_dir=str(output_subdir),
        template_name="lesson.html",
        verbose=False,
    )

    if verbose:
        print(f"  ✓ Week {week} {day:8s} → {Path(pdf_path).name}")

    return pdf_path


def main():
    import argparse

    parser = argparse.ArgumentParser(description="Render ELA weeks 24-32 to PDFs")
    parser.add_argument(
        "--weeks",
        type=str,
        default=None,
        help="Comma-separated week numbers to render (default: all 24-32)",
    )
    parser.add_argument("--dry", action="store_true", help="List files without rendering")

    args = parser.parse_args()

    # Determine which weeks to render
    if args.weeks:
        week_nums = [int(w.strip()) for w in args.weeks.split(",")]
    else:
        week_nums = list(range(24, 33))

    # Find matching outline files
    outlines = []
    for w in week_nums:
        pattern = f"W{w}_*.json"
        matches = sorted(OUTLINES_DIR.glob(pattern))
        outlines.extend(matches)

    if not outlines:
        print(f"❌ No outline files found for weeks {week_nums}")
        print(f"   Looking in: {OUTLINES_DIR}")
        sys.exit(1)

    print(f"Found {len(outlines)} outline files for weeks {week_nums}")

    if args.dry:
        for f in outlines:
            print(f"  {f.name}")
        return

    # Render
    errors = []
    success = 0
    for outline_path in outlines:
        try:
            render_week_weekly(outline_path, verbose=True)
            success += 1
        except Exception as e:
            errors.append((outline_path.name, str(e)))
            print(f"  ❌ {outline_path.name}: {e}")

    # Summary
    print(f"\n{'='*50}")
    print(f"Rendered: {success}/{len(outlines)}")
    if errors:
        print(f"Errors: {len(errors)}")
        for name, err in errors:
            print(f"  - {name}: {err}")


if __name__ == "__main__":
    main()
