#!/usr/bin/env python3
"""
L'Acqua Marina - Render pipeline.

Uso:
  python render.py --template vol1-typography --ratio 1x1 --variant base \
    --data '{"headline":"Patrimonio <em>real</em>","kicker":"MULTIPROPRIEDADE","meta_l":"VOLUME I","meta_r":"ABADIANIA / GO","post_id":"p01"}' \
    --output ./out/p01-1x1.png

Ratios:
  1x1  -> 1080x1080
  4x5  -> 1080x1350
  9x16 -> 1080x1920

O render usa device_scale_factor=2 internamente, resultando em PNG 2x (2160x2160 para 1x1 etc).

Variables dentro do template sao substituidas com replace simples:
  {{RATIO}}, {{VARIANT}}, {{POST_ID}}, {{META_TOP_L}}, {{META_TOP_R}},
  {{HEADLINE}}, {{KICKER}}, {{ATTRIBUTION}}, {{CTA_TEXT}}, {{PHOTO_URL}},
  {{PHOTO_FILTER}}, {{OVERLAY_MODE}}, {{SLOT_CONTENT}}

Dependencies:
  pip install playwright --break-system-packages
  playwright install chromium
"""
import argparse
import json
import re
import sys
from pathlib import Path

try:
    from playwright.sync_api import sync_playwright
except ImportError:
    print("Erro: playwright nao instalado. Rode: pip install playwright --break-system-packages && playwright install chromium")
    sys.exit(1)

SCRIPT_DIR = Path(__file__).parent
SKILL_DIR = SCRIPT_DIR.parent
TEMPLATES_DIR = SKILL_DIR / "templates"

RATIO_MAP = {
    "1x1": (1080, 1080),
    "4x5": (1080, 1350),
    "9x16": (1080, 1920),
}

def render_template(template_name: str, ratio: str, variant: str, data: dict) -> str:
    """Load HTML template and substitute variables."""
    tpl_path = TEMPLATES_DIR / f"{template_name}.html"
    if not tpl_path.exists():
        raise FileNotFoundError(f"Template nao encontrado: {tpl_path}")

    html = tpl_path.read_text(encoding="utf-8")

    # Substitute all variables
    substitutions = {
        "{{RATIO}}": ratio.replace("x", "").replace(":", ""),
        "{{VARIANT}}": variant,
        "{{POST_ID}}": data.get("post_id", "").upper(),
        "{{HEADLINE}}": data.get("headline", ""),
        "{{KICKER}}": data.get("kicker", ""),
        "{{ATTRIBUTION}}": data.get("attribution", ""),
        "{{CTA_TEXT}}": data.get("cta_text", ""),
        "{{META_L}}": data.get("meta_l", ""),
        "{{META_R}}": data.get("meta_r", ""),
        "{{META_TOP_L}}": data.get("meta_top_l", data.get("meta_l", "")),
        "{{META_TOP_R}}": data.get("meta_top_r", data.get("meta_r", "")),
        "{{PHOTO_URL}}": data.get("photo_url", ""),
        "{{PHOTO_FILTER}}": data.get("photo_filter", "low-sat"),
        "{{OVERLAY_MODE}}": data.get("overlay_mode", ""),
        "{{SLOT_CONTENT}}": data.get("slot_content", ""),
    }
    for k, v in substitutions.items():
        html = html.replace(k, str(v))

    # Conditional blocks {{#IF_X}}...{{/IF_X}} - keep if value truthy
    def cond(match):
        flag = match.group(1)
        body = match.group(2)
        key = flag.lower().replace("if_", "")
        val = data.get(key) or data.get(flag.lower()) or ""
        return body if val else ""

    html = re.sub(r"\{\{#(IF_[A-Z_]+)\}\}(.*?)\{\{/\1\}\}", cond, html, flags=re.DOTALL)

    # Ativa IF_KICKER automaticamente se kicker existe, etc.
    if data.get("kicker"):
        html = html.replace("{{#IF_KICKER}}", "").replace("{{/IF_KICKER}}", "")
    if data.get("attribution"):
        html = html.replace("{{#IF_ATTRIBUTION}}", "").replace("{{/IF_ATTRIBUTION}}", "")
    if data.get("cta_text"):
        html = html.replace("{{#IF_CTA}}", "").replace("{{/IF_CTA}}", "")
    if variant == "quote":
        html = html.replace("{{#IF_QUOTE}}", "").replace("{{/IF_QUOTE}}", "")

    # Limpa qualquer IF restante
    html = re.sub(r"\{\{#IF_[A-Z_]+\}\}.*?\{\{/IF_[A-Z_]+\}\}", "", html, flags=re.DOTALL)

    return html

def render_to_png(html: str, ratio: str, output: Path, scale: int = 2):
    width, height = RATIO_MAP[ratio]
    output.parent.mkdir(parents=True, exist_ok=True)

    # Save HTML for debug
    debug_html = output.with_suffix(".html")
    debug_html.write_text(html, encoding="utf-8")

    with sync_playwright() as p:
        browser = p.chromium.launch()
        context = browser.new_context(
            viewport={"width": width, "height": height},
            device_scale_factor=scale,
        )
        page = context.new_page()
        page.set_content(html, wait_until="networkidle")
        page.wait_for_timeout(400)  # ensure fonts settle
        canvas = page.locator("#canvas")
        canvas.screenshot(path=str(output), omit_background=False)
        browser.close()

    print(f"OK: {output} ({width*scale}x{height*scale})")

def main():
    parser = argparse.ArgumentParser(description="L'Acqua Marina post renderer")
    parser.add_argument("--template", required=True, help="vol1-typography | vol2-disruptive | vol3-editorial")
    parser.add_argument("--ratio", required=True, choices=list(RATIO_MAP.keys()))
    parser.add_argument("--variant", default="base", help="CSS class modifier: base, quote, diagonal, magazine, pull-quote, cinema-quote, etc.")
    parser.add_argument("--data", required=True, help="JSON inline com variaveis")
    parser.add_argument("--output", required=True, help="Caminho do PNG final")
    parser.add_argument("--scale", type=int, default=2)
    args = parser.parse_args()

    data = json.loads(args.data)
    html = render_template(args.template, args.ratio, args.variant, data)
    render_to_png(html, args.ratio, Path(args.output), scale=args.scale)

if __name__ == "__main__":
    main()
