#!/usr/bin/env python3
"""
abrir_preview.py — gera HTML auto-carregador que abre .excalidraw no Excalidraw embedded.

Roda no browser local, renderiza a cena interativa em alta-fidelidade,
permite editar/exportar. Mais util que screenshot estatica.

Uso:
    python3 abrir_preview.py --entrada diagrama.excalidraw [--abrir]
"""

import argparse
import base64
import json
import subprocess
import sys
from pathlib import Path

HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Preview Excalidraw Imperatriz — {nome}</title>
<style>
  * {{ margin: 0; padding: 0; box-sizing: border-box; }}
  body {{ font-family: -apple-system, sans-serif; background: #1A1A1A; color: #FAF8F3; }}
  .topbar {{
    padding: 16px 24px; background: #0F0F0F; border-bottom: 2px solid #C9A961;
    display: flex; justify-content: space-between; align-items: center;
  }}
  .topbar h1 {{ font-size: 18px; color: #C9A961; }}
  .topbar small {{ color: #87837C; font-size: 12px; }}
  .acoes {{ display: flex; gap: 12px; }}
  .btn {{
    background: #C9A961; color: #1A1A1A; padding: 8px 16px;
    border: none; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 13px;
  }}
  .btn:hover {{ background: #E0BD6C; }}
  #excalidraw {{ position: absolute; top: 60px; left: 0; right: 0; bottom: 0; }}
</style>
</head>
<body>
  <div class="topbar">
    <div>
      <h1>{nome}</h1>
      <small>arquivo: {caminho} — {n_elementos} elementos · paleta Imperatriz</small>
    </div>
    <div class="acoes">
      <button class="btn" onclick="exportarPNG()">Baixar PNG</button>
      <button class="btn" onclick="exportarSVG()">Baixar SVG</button>
      <button class="btn" onclick="window.open('https://excalidraw.com', '_blank')">Abrir no excalidraw.com</button>
    </div>
  </div>
  <div id="excalidraw"></div>

  <script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
  <script src="https://unpkg.com/@excalidraw/excalidraw@0.17.0/dist/excalidraw.production.min.js"></script>

  <script>
    const cena = {cena_json};
    let api;

    const App = () => {{
      return React.createElement(ExcalidrawLib.Excalidraw, {{
        initialData: cena,
        excalidrawAPI: (a) => {{ api = a; }},
        theme: cena.appState?.theme || "light",
        viewModeEnabled: false,
        zenModeEnabled: false,
        gridModeEnabled: true,
      }});
    }};

    const root = ReactDOM.createRoot(document.getElementById("excalidraw"));
    root.render(React.createElement(App));

    async function exportarPNG() {{
      const blob = await ExcalidrawLib.exportToBlob({{
        elements: api.getSceneElements(),
        appState: api.getAppState(),
        files: api.getFiles(),
        mimeType: "image/png",
      }});
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url; a.download = "{nome_arquivo}.png"; a.click();
    }}

    async function exportarSVG() {{
      const svg = await ExcalidrawLib.exportToSvg({{
        elements: api.getSceneElements(),
        appState: api.getAppState(),
        files: api.getFiles(),
      }});
      const blob = new Blob([svg.outerHTML], {{ type: "image/svg+xml" }});
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url; a.download = "{nome_arquivo}.svg"; a.click();
    }}
  </script>
</body>
</html>"""


def gerar_preview(caminho_excalidraw, caminho_html=None, abrir=False):
    p_in = Path(caminho_excalidraw).expanduser()
    cena = json.loads(p_in.read_text(encoding="utf-8"))

    nome = p_in.stem
    n_elementos = len(cena.get("elements", []))

    html = HTML_TEMPLATE.format(
        nome=nome.replace("-", " ").title(),
        nome_arquivo=nome,
        caminho=p_in.name,
        n_elementos=n_elementos,
        cena_json=json.dumps(cena, ensure_ascii=False),
    )

    if caminho_html is None:
        caminho_html = p_in.with_suffix(".preview.html")
    p_out = Path(caminho_html).expanduser()
    p_out.write_text(html, encoding="utf-8")
    print(f"✓ Preview HTML: {p_out}")

    if abrir:
        subprocess.run(["open", str(p_out)])
        print(f"  Abrindo no navegador padrao...")

    return p_out


def main():
    parser = argparse.ArgumentParser(description="Gera HTML preview de .excalidraw")
    parser.add_argument("--entrada", required=True)
    parser.add_argument("--saida-html", help="Path do .html (default: ao lado do .excalidraw)")
    parser.add_argument("--abrir", action="store_true", help="Abre no navegador padrao")
    args = parser.parse_args()

    gerar_preview(args.entrada, args.saida_html, args.abrir)


if __name__ == "__main__":
    main()
