import marimo

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


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


@app.cell
def _(shell):
    shell(command="ls")
    return


@app.cell
def _(shell):
    shell_widget = shell("""
    sleep 5 && read -p "Ingresa algo: " variable

    """)
    shell_widget
    return (shell_widget,)


@app.cell
def _(shell_widget):
    shell_widget.close()
    return


@app.cell
def _():
    print("hola")
    return


@app.cell
def _(mo):
    cmd_input = mo.ui.text(value="echo 'Hola desde ShellWidget!'", label="Comando")
    workdir_input = mo.ui.text(value=".", label="Directorio de trabajo (opcional)")
    run_btn = mo.ui.run_button(label="Ejecutar comando")

    mo.vstack([cmd_input, workdir_input, run_btn])
    return cmd_input, run_btn, workdir_input


@app.cell
def _(cmd_input, mo, run_btn, shell, workdir_input):
    # Importante: accede a .value en otra celda
    if not run_btn.value:
        mo.md("Pulsa **Ejecutar comando**")
    else:
        # Instanciar el widget Shell cuando se pulse el botón
        # Shell ejecuta y streamea la salida en la celda
        shell(cmd_input.value, working_directory=workdir_input.value)
    return


@app.cell
def _(mo):
    # import marimo as mo
    # from moutils import shell

    cmd = mo.ui.text("date", label="Comando (auto)")
    cmd
    return (cmd,)


@app.cell
def _(cmd, shell):
    # Cada cambio en cmd.value re-ejecuta esta celda
    shell(cmd.value)
    return


@app.cell
def _():
    import asyncio
    from moutils import ShellWidget
    return ShellWidget, asyncio


@app.cell
def _(ShellWidget, asyncio):
    def autorun_shell(command: str, working_directory: str = ".") -> ShellWidget:
        w = ShellWidget(command, working_directory)

        # Programar la ejecución inmediatamente, respetando el event loop actual
        try:
            loop = asyncio.get_event_loop()
            if loop.is_running():
                loop.create_task(w._execute_command_async())
            else:
                loop.run_until_complete(w._execute_command_async())
        except RuntimeError:
            asyncio.run(w._execute_command_async())

        return w
    return (autorun_shell,)


@app.cell
def _(autorun_shell):
    autorun_shell("date", working_directory=".")
    return


@app.cell
def _():
    return


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