import marimo

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


@app.cell
def _():
    import marimo as mo
    return (mo,)


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""# Grafana: Inicialización automática 🚀""")
    return


@app.cell
def _():
    import os
    import yaml
    import subprocess
    from pathlib import Path

    # ==== Parámetros ====
    PUERTO_GRAFANA = 33000  # puerto host -> 3000 del contenedor
    SERVICIO = "grafana_srv"
    ADMIN_USER = "admin"
    ADMIN_PASSWORD = "admin123"
    RUTA_PROYECTO = Path(".").resolve()

    return (
        ADMIN_PASSWORD,
        ADMIN_USER,
        Path,
        PUERTO_GRAFANA,
        RUTA_PROYECTO,
        SERVICIO,
        subprocess,
        yaml,
    )


@app.cell
def _(Path, yaml):
    def crear_docker_compose(ruta: Path, servicio: str, puerto_host: int, admin_user: str, admin_password: str):
        compose = {
            "version": "3.8",
            "services": {
                servicio: {
                    "image": "grafana/grafana:latest",
                    "container_name": servicio,
                    "restart": "always",
                    "ports": [f"{puerto_host}:3000"],
                    "environment": {
                        "GF_SECURITY_ADMIN_USER": admin_user,
                        "GF_SECURITY_ADMIN_PASSWORD": admin_password,
                        "GF_USERS_ALLOW_SIGN_UP": "false",
                        "GF_INSTALL_PLUGINS": "grafana-piechart-panel,grafana-worldmap-panel",
                    },
                    "volumes": [
                        "grafana_data:/var/lib/grafana",
                    ],
                }
            },
            "volumes": {"grafana_data": {}}
        }

        (ruta / "docker-compose.yml").write_text(yaml.dump(compose, sort_keys=False), encoding="utf-8")

    return (crear_docker_compose,)


@app.cell
def _(Path, subprocess):
    def construir_y_levantar(ruta: Path):
        def _run(cmd):
            subprocess.run(cmd, cwd=ruta, check=True)

        try:
            _run(["docker", "compose", "build"])
            _run(["docker", "compose", "up", "-d"])
        except Exception:
            _run(["docker-compose", "build"])
            _run(["docker-compose", "up", "-d"])

    return (construir_y_levantar,)


@app.cell
def _(ADMIN_PASSWORD, ADMIN_USER, PUERTO_GRAFANA, RUTA_PROYECTO, SERVICIO, construir_y_levantar, crear_docker_compose):
    if __name__ == "__main__":
        RUTA_PROYECTO.mkdir(parents=True, exist_ok=True)
        crear_docker_compose(RUTA_PROYECTO, SERVICIO, PUERTO_GRAFANA, ADMIN_USER, ADMIN_PASSWORD)
        construir_y_levantar(RUTA_PROYECTO)
        print(f"✅ Grafana inicializado en http://localhost:{PUERTO_GRAFANA} (usuario: {ADMIN_USER}, contraseña: {ADMIN_PASSWORD})")
    return


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