"""
Jinja2 템플릿 렌더러 — templates_staging/ 검증용.

사용법:
    python render.py {pattern_id} {example_suffix}

    예:
    python render.py cards-3col-persona example
        → templates_staging/cards-3col-persona.example.yaml 데이터로
          templates_staging/cards-3col-persona.html.j2 템플릿 렌더
        → 결과: templates_staging/_renders/cards-3col-persona.example.html

    python render.py cards-3col-persona example-no-photos
        → 사진 없는 케이스 검증

작업 디렉토리: figma_to_html_agent/templates_staging/
"""

import os
import sys
from pathlib import Path

try:
    import yaml
except ImportError:
    print("yaml 미설치. pip install pyyaml")
    sys.exit(1)

try:
    from jinja2 import Template
except ImportError:
    print("jinja2 미설치. pip install jinja2")
    sys.exit(1)


def render(pattern_id: str, example_suffix: str = "example") -> str:
    base = Path(__file__).parent

    template_path = base / f"{pattern_id}.html.j2"
    data_path = base / f"{pattern_id}.{example_suffix}.yaml"
    output_dir = base / "_renders"
    output_dir.mkdir(exist_ok=True)
    output_path = output_dir / f"{pattern_id}.{example_suffix}.html"

    if not template_path.exists():
        raise FileNotFoundError(f"템플릿 없음: {template_path}")
    if not data_path.exists():
        raise FileNotFoundError(f"데이터 없음: {data_path}")

    with open(template_path, "r", encoding="utf-8") as f:
        template = Template(f.read())

    with open(data_path, "r", encoding="utf-8") as f:
        data = yaml.safe_load(f)

    html = template.render(**data)

    with open(output_path, "w", encoding="utf-8") as f:
        f.write(html)

    print(f"✓ 렌더 완료: {output_path}")
    return str(output_path)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(__doc__)
        sys.exit(1)
    pattern_id = sys.argv[1]
    suffix = sys.argv[2] if len(sys.argv) > 2 else "example"
    render(pattern_id, suffix)
