import marimo

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


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


@app.cell
def _():
    import sys
    import subprocess
    from pathlib import Path
    from importlib import import_module
    from typing import Dict, Any, Iterable, Tuple, Optional
    import shutil

    def _prefer_local_path(pkg_name: str, repo_path: Path) -> Optional[str]:
        """Insert repo/src or repo into sys.path (front) if it contains the package folder."""
        for cand in (repo_path / "src", repo_path):
            if (cand / pkg_name).exists():
                sys.path.insert(0, str(cand))
                return str(cand)
        return None

    def _purge_loaded(pkg_name: str) -> None:
        """Remove any already-loaded modules for this package."""
        for k in list(sys.modules):
            if k == pkg_name or k.startswith(pkg_name + "."):
                del sys.modules[k]

    def import_local_libs(
        libs: Dict[str, str],
        install_with_uv: bool = False,
        uv_extra_args: Iterable[str] = (),
    ) -> Dict[str, Any]:
        """
        Force-import local libraries from given repos.
        - libs: dict { 'package_name': '/abs/path/to/repo' }
        - install_with_uv: if True, runs `uv pip install -e <repo>`
          (not required for local dev if sys.path injection is enough)
        - uv_extra_args: extra args for uv, e.g. ['--constraint', 'constraints.txt']
        Returns: dict { 'package_name': imported_module }
        """
        imported: Dict[str, Any] = {}
        uv_bin = shutil.which("uv")

        for name, repo in libs.items():
            repo_path = Path(repo).resolve()
            if not repo_path.exists():
                raise FileNotFoundError(f"[import_local] Repo not found: {repo_path}")

            _purge_loaded(name)
            added = _prefer_local_path(name, repo_path)
            if not added:
                raise ModuleNotFoundError(
                    f"[import_local] Could not find package folder '{name}' in "
                    f"'{repo_path}/src' or '{repo_path}'. Check your repo layout."
                )

            if install_with_uv:
                if not uv_bin:
                    raise RuntimeError("uv not found in PATH, but install_with_uv=True.")
                # Install editable using uv (no pip required).
                # This installs into uv's target environment. For pure local dev,
                # you can keep install_with_uv=False and rely on sys.path injection.
                subprocess.run(
                    [uv_bin, "pip", "install", "-e", str(repo_path), *uv_extra_args],
                    check=True,
                )

            # Import the top-level package to ensure it resolves from the local path
            imported[name] = import_module(name)

        return imported
    return (import_local_libs,)


@app.cell
def _(import_local_libs):
    LIBS = {
        "moutils": "/home/lucas/DataProyects/git_proyects/moutils"
    }

    import_local_libs(LIBS)

    # Ahora ya puedes importar normal
    from moutils import shell, ShellWidget
    return (ShellWidget,)


@app.cell
def _():
    bash_code = """#!/bin/bash

    # Espera input del usuario
    read -p "Write the host to ping" destino

    # Ejecuta ping indefinidamente
    ping "$destino"

    """
    return (bash_code,)


@app.cell
def _(bash_code):
    import os

    # Crear la carpeta scripts si no existe
    os.makedirs("scripts", exist_ok=True)

    # Ruta del archivo .sh dentro de scripts
    script_path = os.path.join("scripts", "mi_script.sh")

    # Guardar el contenido en el archivo
    with open(script_path, "w") as f:
        f.write(bash_code)

    # Dar permisos de ejecución
    os.chmod(script_path, 0o755)

    print(f"Script guardado en {script_path} y listo para ejecutarse.")
    return


@app.cell
def _(ShellWidget):
    console = ShellWidget(command="bash -x ./scripts/mi_script.sh", run=True)
    console
    return


@app.cell
def _():
    # console.kill()
    return


@app.cell
def _():
    return


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