"""
Simple Gradio UI/API for lunamint.

Run:
  python gradio_app.py

Then open the printed URL. The interface also exposes a JSON API.
"""
import tempfile
from pathlib import Path

import gradio as gr

from lunamint.scripting import render_script_to_svg_html


def _generate(script: str, export_png: bool):
  if not script or not script.strip():
    raise gr.Error("Script is required")

  out_dir = Path(tempfile.mkdtemp(prefix="eisen_"))
  svg_path, html_path = render_script_to_svg_html(script, out_dir)
  png_path = None
  if export_png:
    try:
      import cairosvg

      png_path = out_dir / "eisen.png"
      cairosvg.svg2png(url=str(svg_path), write_to=str(png_path))
    except Exception as exc:
      raise gr.Error(f"PNG export failed: {exc}")

  preview_html = (
    "<div style='display:flex;align-items:center;justify-content:center;height:100%;'>"
    "<div style='border:1px solid #ddd;border-radius:12px;padding:12px;background:#fff;max-width:95%;max-height:95%;'>"
    f"{svg_path.read_text(encoding='utf-8')}"
    "</div></div>"
  )

  return preview_html, str(svg_path), str(png_path) if png_path else None


def build_ui():
    with gr.Blocks(title="Banknote Generator") as demo:
        gr.Markdown("# Banknote Generator\nGenerate front/back SVG+PNG using lunamint.")

        with gr.Tab("Editor"):
            default_script = ""
            script_path = Path(__file__).resolve().parents[1] / "my_mints" / "eisen.sample"
            if script_path.exists():
                default_script = script_path.read_text(encoding="utf-8")

            script_editor = gr.Textbox(
                label="EisenScript",
                value=default_script,
                lines=16,
            )

        with gr.Tab("Preview"):
            preview_panel = gr.HTML(
                "<div style='height:100%;display:flex;align-items:center;justify-content:center;color:#888;'>Generate to preview</div>",
                sanitize=False,
            )

        with gr.Tab("Save"):
            export_png = gr.Checkbox(label="Export PNG", value=False)
            run_btn = gr.Button("Generate")
            svg_file = gr.File(label="SVG output")
            png_file = gr.File(label="PNG output")

        run_btn.click(
            _generate,
            inputs=[
            script_editor,
            export_png,
            ],
          outputs=[preview_panel, svg_file, png_file],
        )

    return demo


if __name__ == "__main__":
    app = build_ui()
    app.launch()
