import marimo

__generated_with = "0.15.1"
app = marimo.App(width="medium")


@app.cell
def _():
    import marimo as mo
    from d2_widget import Widget
    import pathlib
    import datetime as dt

    return Widget, mo, pathlib


@app.cell(hide_code=True)
def _(mo):
    # Definición por defecto (puedes editarla en el textarea)
    d2_source_default = """
    # Ajustes de layout
    direction: right

    # Nodos
    app: {
      label: "Ingesta"
      shape: rectangle
    }
    db: {
      label: "PostgreSQL"
      shape: cylinder
    }
    dashboard: {
      label: "Metabase"
    }

    # Enlaces
    app -> db: "escribe"
    db -> dashboard: "lee"
    """

    # Widgets de UI
    editor = mo.ui.text_area(value=d2_source_default, label="Definición D2", full_width=True)
    theme_id = mo.ui.number(value=200, label="themeID (D2)")
    pad_px = mo.ui.number(value=8, label="Padding")
    sketch_mode = mo.ui.checkbox(label="Sketch (boceto)", value=False)
    animate_edges = mo.ui.checkbox(label="Animar aristas", value=True)

    export_name = mo.ui.text(value="diagrama.svg", label="Archivo SVG")
    export_button = mo.ui.run_button(label="Exportar SVG")

    # Layout
    mo.ui.tabs({
        "Editor": mo.vstack([
            mo.md("## Diagrama D2"),
            editor,
        ]),
        "Opciones": mo.vstack([
            mo.hstack([theme_id, pad_px, sketch_mode, animate_edges], justify="start", gap="1rem"),
            mo.md("Configura opciones del compilador D2."),
        ]),
        "Exportar": mo.vstack([
            mo.hstack([export_name, export_button], gap="1rem"),
        ]),
    })

    return editor, export_button, export_name, pad_px, sketch_mode, theme_id


@app.cell
def _(pad_px, sketch_mode, theme_id):
    compile_options = {
        "themeID": int(theme_id.value),
        "pad": int(pad_px.value),
        "sketch": bool(sketch_mode.value),
    }

    return (compile_options,)


@app.cell
def _(Widget, compile_options, editor):
    diagram_widget = Widget(editor.value, compile_options)
    diagram_widget
    return (diagram_widget,)


@app.cell
def _(diagram_widget, export_button, export_name, mo, pathlib):
    if export_button.value:
        svg_text = diagram_widget.svg
        out_path = pathlib.Path(export_name.value)
        out_path.write_text(svg_text, encoding="utf-8")
        mo.md(f"### SVG exportado\n[Descargar SVG]({out_path})")
    else:
        mo.md("Pulsa **Exportar SVG** para guardar el archivo.")
    return


if __name__ == "__main__":
    app.run()
