#!/usr/bin/env python3
"""
Générateur de fiche-guide PDF à partir d'un export JSON de carte Uluana.
Usage: python3 generate_card_pdf.py export_cartes_C-087_a_C-087.json output.pdf
Réutilisable pour n'importe quelle carte ayant la même structure (detail / guide / examples).
"""
import json
import sys
from pathlib import Path
from jinja2 import Template
from weasyprint import HTML

TEMPLATE_PATH = Path(__file__).parent / "template.html"
CSS_PATH = Path(__file__).parent / "card-guide.css"
CATEGORIES_PATH = Path(__file__).parent / "categories.json"

DIFFICULTY_LABELS = {1: "Facile", 2: "Intermédiaire", 3: "Avancé"}


def build_context(card: dict, enrichment: dict | None = None) -> dict:
    detail = card.get("detail", {})
    guide = card.get("guide", {})
    examples = card.get("examples", [])
    enrichment = enrichment or {}

    sections = {s["type"]: s for s in detail.get("sections", [])}
    method_steps = sections.get("method", {}).get("steps", [])
    tips = sections.get("tips", {}).get("items", [])
    warnings = sections.get("warning", {}).get("items", [])

    questions = guide.get("cadrage", {}).get("questions", [])
    comment_faire = enrichment.get("comment_faire_par_etape", {})

    # Fusion : étape méthode + question de cadrage correspondante (même rang)
    # + "comment faire concrètement" (nouveau champ, cf. enrichissement)
    merged_steps = []
    for i, s in enumerate(method_steps):
        q = questions[i] if i < len(questions) else None
        merged_steps.append({
            "num": s["step"],
            "title": s["title"],
            "content": s["content"],
            "reflect": q.get("question") if q else None,
            "howto": comment_faire.get(str(s["step"]), []),
        })

    example = examples[0] if examples else None

    categories = json.loads(CATEGORIES_PATH.read_text(encoding="utf-8")) if CATEGORIES_PATH.exists() else {}
    category_id = card.get("category_id")

    return {
        "title": card.get("title"),
        "label": detail.get("uluana_label"),
        "category_label": categories.get(category_id, category_id),
        "difficulty": card.get("difficulty", 1),
        "difficulty_label": DIFFICULTY_LABELS.get(card.get("difficulty", 1), ""),
        "tags": card.get("tags", []),
        "intro": detail.get("intro"),
        "prerequis": guide.get("contexte_uluana", {}).get("prerequis", []),
        "steps": merged_steps,
        "premier_pas": guide.get("premier_pas", {}),
        "tips": tips,
        "warnings": warnings,
        "example": example,
        "exemples_concrets": enrichment.get("exemples_concrets", []),
        "indicateurs": guide.get("mesure", {}).get("indicateurs", []),
        "liens_avant": guide.get("liens_cards", {}).get("avant", []),
        "liens_apres": guide.get("liens_cards", {}).get("apres", []),
    }


def main():
    if len(sys.argv) < 3:
        print("Usage: generate_card_pdf.py <input.json> <output.pdf> [card_id] [--enrich enrichment.json]")
        sys.exit(1)

    input_path, output_path = sys.argv[1], sys.argv[2]
    rest = sys.argv[3:]
    card_id_filter = None
    enrich_path = None
    if "--enrich" in rest:
        idx = rest.index("--enrich")
        enrich_path = rest[idx + 1]
        rest = rest[:idx]
    if rest:
        card_id_filter = rest[0]

    with open(input_path, encoding="utf-8") as f:
        cards = json.load(f)

    card = cards[0] if not card_id_filter else next(
        c for c in cards if c["id"] == card_id_filter
    )

    enrichment = None
    if enrich_path:
        with open(enrich_path, encoding="utf-8") as f:
            enrichment = json.load(f)

    context = build_context(card, enrichment)

    template = Template(TEMPLATE_PATH.read_text(encoding="utf-8"))
    html_str = template.render(**context)

    HTML(string=html_str, base_url=str(TEMPLATE_PATH.parent)).write_pdf(output_path)
    print(f"PDF généré : {output_path}")


if __name__ == "__main__":
    main()
