"""ICEBERG POS - Launcher silencioso (sin ventanas de consola).

Uso: pythonw.exe _launcher.py [modo]
  modo: servidor | caja | completa (default: completa)

Si no se pasa argumento, lee el modo desde config/mode.txt.
"""
import subprocess
import os
import sys
import time

base = os.path.dirname(os.path.abspath(__file__))
py = os.path.join(base, "runtime", "python.exe")
CREATE_NO_WINDOW = 0x08000000


def _read_mode():
    """Lee modo de config/mode.txt si existe."""
    mode_file = os.path.join(base, "config", "mode.txt")
    if os.path.exists(mode_file):
        try:
            with open(mode_file, "r") as f:
                val = f.read().strip().lower()
            if val in ("servidor", "caja", "completa"):
                return val
        except Exception:
            pass
    return "completa"


mode = sys.argv[1] if len(sys.argv) > 1 else _read_mode()

os.makedirs(os.path.join(base, "logs"), exist_ok=True)

if mode in ("servidor", "completa"):
    srv_log = open(os.path.join(base, "logs", "server.log"), "w")
    subprocess.Popen(
        [py, "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"],
        cwd=os.path.join(base, "server"),
        creationflags=CREATE_NO_WINDOW,
        stdout=srv_log, stderr=srv_log,
    )
    # Esperar a que el servidor este listo (hasta 30s)
    import urllib.request
    for _ in range(30):
        time.sleep(1)
        try:
            urllib.request.urlopen("http://127.0.0.1:8000/api/health", timeout=2)
            break
        except Exception:
            pass

if mode in ("caja", "completa"):
    subprocess.Popen(
        [py, "agent.py"],
        cwd=os.path.join(base, "agent"),
        creationflags=CREATE_NO_WINDOW,
    )
    time.sleep(2)

    subprocess.Popen(
        [py, "main.py"],
        cwd=os.path.join(base, "app"),
        creationflags=CREATE_NO_WINDOW,
    )
