#!/usr/bin/env python3
"""Launch Dealboard. Auto-installs deps on first run."""
import os
import shutil
import sys
import subprocess
import time
import urllib.request
import webbrowser

BASE = os.path.dirname(os.path.abspath(__file__))
IS_WIN = sys.platform == "win32"

if IS_WIN:
    PY = os.path.join(BASE, "python", "pythonw.exe")
    PY_CONSOLE = os.path.join(BASE, "python", "python.exe")
    DEPS = os.path.join(BASE, "deps")
else:
    VENV_BIN = os.path.join(BASE, ".venv", "bin")
    PY = os.path.join(VENV_BIN, "python")
    DEPS = None

PORT = "8765"
URL = f"http://127.0.0.1:{PORT}"
REQS = os.path.join(BASE, "backend", "requirements.txt")

def ensure_deps():
    if not IS_WIN:
        if os.path.exists(PY):
            return
        # Auto-setup on macOS
        sys_py = shutil.which("python3") or shutil.which("python")
        if not sys_py:
            print("Python not found. Install from python.org.")
            sys.exit(1)
        subprocess.run([sys_py, "-m", "venv", os.path.join(BASE, ".venv")], cwd=BASE, capture_output=True)
        subprocess.run([PY, "-m", "pip", "install", "-r", REQS], cwd=BASE, capture_output=True)
        return

    # Windows: embedded python
    if os.path.exists(os.path.join(DEPS, "fastapi")):
        return

    # First run — install deps silently
    os.makedirs(DEPS, exist_ok=True)

    # Enable site + add deps path
    pth = os.path.join(BASE, "python", "python311._pth")
    if os.path.exists(pth):
        with open(pth, "r") as f:
            lines = f.read().splitlines()
        new_lines = []
        seen_deps = False
        for line in lines:
            if line.strip().startswith("#import site"):
                new_lines.append("import site")
            else:
                new_lines.append(line)
            if line.strip() == "deps":
                seen_deps = True
        if not seen_deps:
            new_lines.append("deps")
        with open(pth, "w") as f:
            f.write("\n".join(new_lines) + "\n")

    # Install pip if missing
    pip = os.path.join(BASE, "python", "Scripts", "pip.exe")
    if not os.path.exists(pip):
        getpip = os.path.join(BASE, "python", "get-pip.py")
        if not os.path.exists(getpip):
            urllib.request.urlretrieve("https://bootstrap.pypa.io/get-pip.py", getpip)
        subprocess.run([PY_CONSOLE, getpip, "--no-warn-script-location"], cwd=BASE, capture_output=True)

    # Install requirements
    subprocess.run([PY_CONSOLE, "-m", "pip", "install", "-r", REQS, "--target", DEPS, "--no-warn-script-location"], cwd=BASE, capture_output=True)

def main():
    ensure_deps()

    env = os.environ.copy()
    env["PYTHONPATH"] = os.path.join(BASE, "backend")
    if DEPS:
        env["PYTHONPATH"] = DEPS + os.pathsep + env["PYTHONPATH"]

    popen_kwargs = {
        "cwd": BASE,
        "env": env,
        "stdout": subprocess.DEVNULL,
        "stderr": subprocess.DEVNULL,
    }
    if IS_WIN:
        popen_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS

    subprocess.Popen(
        [PY, "-m", "uvicorn", "backend.main:app", "--host", "127.0.0.1", "--port", PORT],
        **popen_kwargs,
    )

    for _ in range(40):
        try:
            urllib.request.urlopen(URL, timeout=1)
            break
        except Exception:
            time.sleep(0.15)

    webbrowser.open(URL)
    time.sleep(86400)

if __name__ == "__main__":
    main()
