"""Hard-reset native stack ports and start host services."""
from __future__ import annotations

import os
import subprocess
import sys
import time
import urllib.request
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
LOG = ROOT / ".runtime" / "logs"
LOG.mkdir(parents=True, exist_ok=True)
PORTS = (8888, 8001, 8180, 5173)


def pids_on_port(port: int) -> list[int]:
    out = subprocess.check_output(["netstat", "-ano"], text=True, errors="replace")
    pids: set[int] = set()
    needle = f":{port}"
    for line in out.splitlines():
        if needle not in line or "LISTENING" not in line.upper():
            continue
        parts = line.split()
        try:
            pids.add(int(parts[-1]))
        except ValueError:
            pass
    return sorted(pids)


def kill_pid(pid: int) -> None:
    if pid <= 0:
        return
    subprocess.run(["taskkill", "/F", "/T", "/PID", str(pid)], check=False, capture_output=True)


def main() -> None:
    print("==> hard stop ports", PORTS)
    for name in ("watchdog.pid", "ai-service.pid", "platform.pid", "gateway.pid", "web.pid"):
        pf = LOG / name
        if pf.is_file():
            try:
                kill_pid(int(pf.read_text(encoding="ascii").strip()))
            except ValueError:
                pass
            pf.unlink(missing_ok=True)

    for port in PORTS:
        for pid in pids_on_port(port):
            print(f"  kill :{port} pid={pid}")
            kill_pid(pid)
    time.sleep(2)

    # leftover listeners
    for port in PORTS:
        for pid in pids_on_port(port):
            print(f"  re-kill :{port} pid={pid}")
            kill_pid(pid)
    time.sleep(1)

    print("==> start-host.ps1 -NoBrowser")
    # Prefer -UseHost path without docker
    ps1 = ROOT / "start-host.ps1"
    proc = subprocess.run(
        [
            "powershell",
            "-NoProfile",
            "-ExecutionPolicy",
            "Bypass",
            "-File",
            str(ps1),
            "-NoBrowser",
        ],
        cwd=str(ROOT),
        check=False,
    )
    if proc.returncode != 0:
        raise SystemExit(f"start-host failed code={proc.returncode}")

    # verify
    for url in (
        "http://127.0.0.1:5173/",
        "http://127.0.0.1:8001/health",
        "http://127.0.0.1:8180/gateway/health",
    ):
        try:
            with urllib.request.urlopen(url, timeout=3) as r:
                print(f"OK  {url} -> {r.status}")
        except Exception as e:
            print(f"FAIL {url} -> {e}")
            raise SystemExit(1)

    # only one listener on 8001
    p8001 = pids_on_port(8001)
    print("listeners :8001 ->", p8001)
    p5173 = pids_on_port(5173)
    print("listeners :5173 ->", p5173)


if __name__ == "__main__":
    main()
