#==========================common.py============================================
# -*- coding: utf-8 -*-
"""
common.py — shared UC-win/Road access layer
============================================
Used by detect.py and brake.py. Two responsibilities:

  1) COM attach (attach-only, never launches a new UC-win instance)
       EgoLink.read() -> ((x, z, dir_x, dir_z, speed_kmh), car, status_msg)
  2) UDP telemetry (Log Export plugin stream)
       Telemetry.poll() keeps per-ID position / speed tracks.
       Speeds use the sim timestamp inside each packet (wall-clock arrival
       time is unreliable under packet bursts).

Coordinate note: COM coordinates and UDP log coordinates are mirrored along
the north-south (Z) axis.  z_internal = MIRROR_C - z_udp  (measured on the
Miyazaki map: 18479.8).
"""

import math
import socket
import subprocess
import time

import win32gui
from win32com.client import Dispatch, GetActiveObject

PROGID_19 = "UCwinRoad.UCwinRoadCom_1901"
PROGID_OLD = "UCwinRoad.F8ApplicationServicesProxy"

CHILD_ID_DEFAULT = "5764"
ADULT_ID_DEFAULT = "5763"
MIRROR_C_DEFAULT = 18479.8   # z_internal = C - z_udp (measured, Miyazaki map)
TELEPORT = 30.0              # m/s — route-loop jump artifact filter


# ---------------------------------------------------------------------------
# process / window helpers
# ---------------------------------------------------------------------------
def ucwin_pids():
    """Set of PIDs of running UCwinRoad.exe processes."""
    out = subprocess.run(
        ["tasklist", "/FI", "IMAGENAME eq UCwinRoad.exe", "/FO", "CSV", "/NH"],
        capture_output=True, text=True,
        creationflags=subprocess.CREATE_NO_WINDOW)
    pids = set()
    for line in out.stdout.splitlines():
        parts = [p.strip('"') for p in line.strip().split('","')]
        if len(parts) >= 2 and parts[0].lower() == "ucwinroad.exe":
            try:
                pids.add(int(parts[1]))
            except ValueError:
                pass
    return pids


def kill_pids(pids):
    for pid in pids:
        subprocess.run(["taskkill", "/PID", str(pid), "/F"],
                       capture_output=True,
                       creationflags=subprocess.CREATE_NO_WINDOW)


def ucwin_window_exists():
    found = []

    def _cb(h, _):
        try:
            if win32gui.GetWindowText(h).startswith("UC-win/Road") \
                    and win32gui.IsWindowVisible(h):
                found.append(h)
        except Exception:
            pass
        return True

    win32gui.EnumWindows(_cb, None)
    return bool(found)


# ---------------------------------------------------------------------------
# COM attach (attach-only, spawn-guarded)
# ---------------------------------------------------------------------------
def attach_only(holder, last_try):
    """Attach to a running UC-win only — never launch a new instance.
    UC-win does not register its object in the ROT, so GetActiveObject fails;
    Dispatch attaches to the running instance. As a safeguard, UCwinRoad.exe
    PIDs are compared before/after Dispatch and any spawned instance is
    killed immediately.  Returns (app or None, status string)."""
    if holder[0] is not None:
        return holder[0], "ok"
    if not ucwin_window_exists():
        return None, "no_window"
    if time.time() - last_try[0] < 3.0:
        return None, "waiting"
    last_try[0] = time.time()
    for progid in (PROGID_19, PROGID_OLD):
        try:
            root = GetActiveObject(progid)
            holder[0] = getattr(root, "ApplicationServices", root)
            return holder[0], "ok"
        except Exception:
            continue
    pids_before = ucwin_pids()
    if not pids_before:
        return None, "no_window"
    if len(pids_before) > 1:
        return None, "multi_instance"
    try:
        root = Dispatch(PROGID_OLD)
    except Exception as e:
        return None, f"attach_fail: {e}"
    spawned = ucwin_pids() - pids_before
    if spawned:
        del root
        kill_pids(spawned)
        return None, "spawn_blocked"
    holder[0] = getattr(root, "ApplicationServices", root)
    return holder[0], "ok"


_STATUS_TEXT = {
    "no_window": "UC-win window not found - waiting",
    "multi_instance": "multiple UC-win instances - close all but one",
    "spawn_blocked": "blocked a new UC-win instance - check Python API registration",
}


class EgoLink:
    """COM link to the driven car. read() never blocks for long and never
    spawns a new UC-win instance."""

    def __init__(self):
        self.holder = [None]
        self.last_try = [0.0]

    def read(self):
        """Returns (ego, car, msg):
             ego = (x, z, dir_x, dir_z, speed_kmh)  or None
             car = COM car object (for actuation)   or None
             msg = status string to show the user   or None (silent retry)
        """
        app, astat = attach_only(self.holder, self.last_try)
        if app is None:
            if astat == "waiting":
                return None, None, None
            if astat.startswith("attach_fail"):
                return None, None, f"COM attach failed ({astat[12:].strip()})"
            return None, None, _STATUS_TEXT.get(astat, astat)
        try:
            car = app.SimulationCore.TrafficSimulation.Driver.CurrentCar
            if car is None:
                return None, None, ("no driver car - start driving "
                                    "(driver's seat view with dashboard)")
            pp = car.Position
            dd = car.Direction
            try:
                vk = float(car.Speed(1))
            except Exception:
                vk = 0.0
            return (pp.X, pp.Z, dd.X, dd.Z, vk), car, None
        except Exception as e:
            self.holder[0] = None
            return None, None, f"COM error ({type(e).__name__}) - reconnecting"


# ---------------------------------------------------------------------------
# UDP telemetry
# ---------------------------------------------------------------------------
class Telemetry:
    """Listens to the Log Export plugin UDP stream and tracks the given IDs.

    Line format (moving objects): [0]=sim_time, [7]=ID, [9,10,11]=x,y,z.
    The driver-car line has a different column layout (ID parses as 0 with
    garbage coordinates) and is rejected by the |x| filter.
    """

    def __init__(self, ids, port=4000, ip="0.0.0.0"):
        self.ids = set(str(i) for i in ids)
        self.pos = {}        # oid -> (t_sim, x, y, z)
        self.spd = {}        # oid -> m/s (sim-timestamp based)
        self.seen = {}       # oid -> wall-clock last receive time
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2 * 1024 * 1024)
        self.sock.bind((ip, port))
        self.sock.setblocking(False)

    def poll(self, budget=3000):
        """Drain pending packets and update tracks."""
        for _ in range(budget):
            try:
                data, _ = self.sock.recvfrom(65536)
            except (BlockingIOError, OSError):
                break
            for line in data.decode("utf-8", errors="ignore").splitlines():
                p = line.split(",")
                if len(p) < 12:
                    continue
                oid = p[7].strip()
                if oid not in self.ids:
                    continue
                try:
                    t = float(p[0])
                    x, y, z = float(p[9]), float(p[10]), float(p[11])
                except ValueError:
                    continue
                if abs(x) > 1e5 or abs(z) > 1e5:
                    continue
                if oid in self.pos:
                    t0, x0, y0, z0 = self.pos[oid]
                    dt = t - t0
                    if 0.01 <= dt <= 1.0:
                        v = math.dist((x, y, z), (x0, y0, z0)) / dt
                        if v <= TELEPORT:
                            self.spd[oid] = v
                self.pos[oid] = (t, x, y, z)
                self.seen[oid] = time.time()

    def fresh(self, oid, stale_sec=2.0):
        """True if this ID has been received within stale_sec."""
        return oid in self.pos and time.time() - self.seen.get(oid, 0) <= stale_sec

    def rel(self, oid, ex, ez, dx, dz, mirror_c=MIRROR_C_DEFAULT):
        """Relative geometry of one pedestrian w.r.t. the ego car.
        Returns (dist, ahead, azimuth_rad, speed) or None.
          ahead   : projection onto the heading (+ = in front)
          azimuth : signed angle from the heading (+ = to the right)
        """
        if not self.fresh(oid):
            return None
        _, x, y, z = self.pos[oid]
        z_int = mirror_c - z                     # mirror conversion
        rx, rz = x - ex, z_int - ez
        d = math.hypot(rx, rz)
        ahead = rx * dx + rz * dz
        az = math.atan2(rx * dz - rz * dx, ahead) if d > 1e-6 else 0.0
        return d, ahead, az, self.spd.get(oid)

    def close(self):
        try:
            self.sock.close()
        except Exception:
            pass
#==========================stereo.py============================================
# -*- coding: utf-8 -*-
"""
stereo.py — stereo-vision distance & speed algorithm (cam_L / cam_R)
=====================================================================
Pure algorithm module (no YOLO import) used by detect.py:

  1) Window capture of the two UC-win view windows cam_L / cam_R
     (PrintWindow with PW_RENDERFULLCONTENT, screen-region fallback —
      UC-win's 3D view is OpenGL, plain BitBlt returns stale content)
  2) Disparity of a person bounding box by template matching the torso
     patch of the left image along the same rows of the right image,
     with sub-pixel parabola refinement
  3) Depth from the pinhole model:
         f_px = (H/2) / tan(vFOV/2)
         Z    = f_px * B / disparity        (B = camera baseline [m])
         X    = (u - cx) * Z / f_px         (lateral position, right +)
         dist = sqrt(X^2 + Z^2)
  4) Speed by linear regression of (X, Z) over a sliding time window:
         crossing speed = dX/dt,  closing speed = -dZ/dt

UC-win view setup this module expects (view editor):
  - two views named cam_L / cam_R, coordinates relative to the driven car
  - cam_L = (lateral -0.25, height +1.6, forward +0.5) m
    cam_R = (lateral +0.25, height +1.6, forward +0.5) m   -> B = 0.50 m
  - identical direction (yaw 0, pitch 0, roll 0) and vertical FOV 45 deg

Standalone test (no YOLO — measures the full-frame center strip):
  python stereo.py
"""

import ctypes
import math
import time
from collections import deque

import numpy as np
import cv2
import win32con
import win32gui
import win32ui

VFOV_DEG_DEFAULT = 45.0     # must match the view's "vertical FOV"
BASELINE_DEFAULT = 0.50     # cam_L ~ cam_R spacing [m]
WIN_L_SUBSTR = "cam_L"
WIN_R_SUBSTR = "cam_R"
MAX_DISPARITY_PX = 200      # search limit (f=870px, B=0.5m -> min range ~2.2 m)
TRACK_WINDOW_S = 0.8        # speed-regression time window [s]

try:
    ctypes.windll.user32.SetProcessDPIAware()   # display-scaling correction
except Exception:
    pass

PW_CLIENTONLY = 1
PW_RENDERFULLCONTENT = 2


# ---------------------------------------------------------------------------
# window find / capture
# ---------------------------------------------------------------------------
def find_window_by_substring(substr, must_prefix="경관 위치"):
    """Find a view window (docked child panels included) whose title starts
    with the UC-win view prefix and contains substr. Windows of other
    programs are never selected even if their title contains substr."""
    found = []

    def _match(hwnd):
        try:
            title = win32gui.GetWindowText(hwnd)
            if title.startswith(must_prefix) and substr.lower() in title.lower():
                found.append((hwnd, title))
        except Exception:
            pass

    def _child_cb(hwnd, _):
        _match(hwnd)
        return True

    def _top_cb(hwnd, _):
        try:
            if win32gui.IsWindowVisible(hwnd):
                _match(hwnd)
                win32gui.EnumChildWindows(hwnd, _child_cb, None)
        except Exception:
            pass
        return True

    win32gui.EnumWindows(_top_cb, None)
    return found[0][0] if found else 0


def _bits_to_frame(bmp, w, h):
    buf = bmp.GetBitmapBits(True)
    return np.frombuffer(buf, dtype=np.uint8).reshape((h, w, 4))[..., :3].copy()


def _capture_printwindow(hwnd):
    """Method 1: PrintWindow + PW_RENDERFULLCONTENT (asks for GPU content)."""
    try:
        l, t, r, b = win32gui.GetClientRect(hwnd)
        w, h = r - l, b - t
        if w < 32 or h < 32:
            return None
        hdc = win32gui.GetWindowDC(hwnd)
        mfc = win32ui.CreateDCFromHandle(hdc)
        mem = mfc.CreateCompatibleDC()
        bmp = win32ui.CreateBitmap()
        bmp.CreateCompatibleBitmap(mfc, w, h)
        mem.SelectObject(bmp)
        ok = ctypes.windll.user32.PrintWindow(
            hwnd, mem.GetSafeHdc(), PW_CLIENTONLY | PW_RENDERFULLCONTENT)
        frame = _bits_to_frame(bmp, w, h) if ok else None
        win32gui.DeleteObject(bmp.GetHandle())
        mem.DeleteDC(); mfc.DeleteDC()
        win32gui.ReleaseDC(hwnd, hdc)
        return frame
    except Exception:
        return None


def _capture_screen_region(hwnd):
    """Method 2: capture the window's screen region from the desktop
    (the window must not be covered by another window)."""
    try:
        l, t, r, b = win32gui.GetClientRect(hwnd)
        w, h = r - l, b - t
        if w < 32 or h < 32:
            return None
        x0, y0 = win32gui.ClientToScreen(hwnd, (0, 0))
        hdc = win32gui.GetDC(0)
        mfc = win32ui.CreateDCFromHandle(hdc)
        mem = mfc.CreateCompatibleDC()
        bmp = win32ui.CreateBitmap()
        bmp.CreateCompatibleBitmap(mfc, w, h)
        mem.SelectObject(bmp)
        mem.BitBlt((0, 0), (w, h), mfc, (x0, y0), win32con.SRCCOPY)
        frame = _bits_to_frame(bmp, w, h)
        win32gui.DeleteObject(bmp.GetHandle())
        mem.DeleteDC(); mfc.DeleteDC()
        win32gui.ReleaseDC(0, hdc)
        return frame
    except Exception:
        return None


def _looks_invalid(frame):
    return frame is None or float(frame.std()) < 3.0


_capture_mode = ["auto"]    # auto -> falls back to screen capture once


def capture_client(hwnd):
    """Capture a window's client area as a BGR ndarray (OpenGL-safe)."""
    if not hwnd:
        return None
    if _capture_mode[0] in ("auto", "print"):
        frame = _capture_printwindow(hwnd)
        if not _looks_invalid(frame):
            _capture_mode[0] = "print"
            return frame
        if _capture_mode[0] == "auto":
            print("[stereo] PrintWindow returned no 3D content - switching to "
                  "screen capture (do not cover the cam windows!)")
            _capture_mode[0] = "screen"
    frame = _capture_screen_region(hwnd)
    return None if _looks_invalid(frame) else frame


class StereoRig:
    """Finds and captures the cam_L / cam_R windows as a synchronized pair."""

    def __init__(self, vfov_deg=VFOV_DEG_DEFAULT, baseline=BASELINE_DEFAULT):
        self.vfov = vfov_deg
        self.baseline = baseline
        self.hwndL = 0
        self.hwndR = 0

    def connected(self):
        return bool(self.hwndL and self.hwndR)

    def find(self):
        self.hwndL = find_window_by_substring(WIN_L_SUBSTR)
        self.hwndR = find_window_by_substring(WIN_R_SUBSTR)
        return self.connected()

    def grab(self):
        """Returns (imgL, imgR, f_px, cx) or None."""
        if not self.connected() and not self.find():
            return None
        imgL = capture_client(self.hwndL)
        imgR = capture_client(self.hwndR)
        if imgL is None or imgR is None:
            self.hwndL = self.hwndR = 0
            return None
        if imgL.shape != imgR.shape:
            h = min(imgL.shape[0], imgR.shape[0])
            w = min(imgL.shape[1], imgR.shape[1])
            imgL, imgR = cv2.resize(imgL, (w, h)), cv2.resize(imgR, (w, h))
        H, W = imgL.shape[:2]
        f_px = (H / 2.0) / math.tan(math.radians(self.vfov) / 2.0)
        return imgL, imgR, f_px, W / 2.0


# ---------------------------------------------------------------------------
# disparity (template matching + sub-pixel refinement)
# ---------------------------------------------------------------------------
def disparity_of_bbox(grayL, grayR, bbox, max_disp=MAX_DISPARITY_PX):
    """Search the left-image bbox patch leftward along the same rows of the
    right image.  Returns (disparity_px, match_score) or (None, 0)."""
    x1, y1, x2, y2 = [int(v) for v in bbox]
    h, w = grayL.shape[:2]
    x1, y1 = max(0, x1), max(0, y1)
    x2, y2 = min(w - 1, x2), min(h - 1, y2)
    if x2 - x1 < 8 or y2 - y1 < 12:
        return None, 0.0

    # use only the torso band (leg animation adds matching noise)
    bh = y2 - y1
    py1, py2 = y1 + int(bh * 0.15), y1 + int(bh * 0.60)
    patch = grayL[py1:py2, x1:x2]
    if patch.size == 0:
        return None, 0.0

    sx1 = max(0, x1 - max_disp)
    strip = grayR[py1:py2, sx1:x2]
    if strip.shape[1] <= patch.shape[1]:
        return None, 0.0

    res = cv2.matchTemplate(strip, patch, cv2.TM_CCOEFF_NORMED)
    _, score, _, max_loc = cv2.minMaxLoc(res)
    xr = sx1 + max_loc[0]
    disp = float(x1 - xr)

    # sub-pixel: parabola interpolation around the peak
    mi = max_loc[0]
    if 0 < mi < res.shape[1] - 1:
        s0, s1, s2 = res[0 if res.shape[0] == 1 else max_loc[1], mi - 1:mi + 2]
        denom = (s0 - 2 * s1 + s2)
        if abs(denom) > 1e-9:
            disp += 0.5 * (s2 - s0) / denom

    if disp <= 0.5:
        return None, score
    return disp, float(score)


def measure_bbox(imgL, imgR, bbox, f_px, cx, baseline):
    """Full stereo measurement of one bounding box.
    Returns dict(z, x_lat, dist, disparity, score, est_height) or None."""
    grayL = cv2.cvtColor(imgL, cv2.COLOR_BGR2GRAY)
    grayR = cv2.cvtColor(imgR, cv2.COLOR_BGR2GRAY)
    disp, score = disparity_of_bbox(grayL, grayR, bbox)
    if disp is None:
        return None
    Z = f_px * baseline / disp
    u = (bbox[0] + bbox[2]) / 2.0
    X = (u - cx) * Z / f_px
    return {
        "z": Z,
        "x_lat": X,
        "dist": math.hypot(X, Z),
        "disparity": disp,
        "score": score,
        "est_height": (bbox[3] - bbox[1]) * Z / f_px,
        "azimuth": math.atan2(X, Z),
    }


# ---------------------------------------------------------------------------
# speed estimation (per-target sliding-window regression)
# ---------------------------------------------------------------------------
class SpeedTracker:
    """Keeps a short (t, X, Z) history per target key and fits straight
    lines to estimate crossing speed (dX/dt) and closing speed (-dZ/dt)."""

    def __init__(self, window_s=TRACK_WINDOW_S):
        self.window = window_s
        self.tracks = {}     # key -> deque[(t, X, Z)]

    def update(self, key, x_lat, z, now=None):
        now = time.time() if now is None else now
        tr = self.tracks.setdefault(key, deque())
        tr.append((now, x_lat, z))
        while tr and now - tr[0][0] > self.window:
            tr.popleft()
        if len(tr) < 4 or tr[-1][0] - tr[0][0] < 0.2:
            return None, None
        ts = np.array([p[0] for p in tr]); ts -= ts[0]
        xs = np.array([p[1] for p in tr])
        zs = np.array([p[2] for p in tr])
        vx = float(np.polyfit(ts, xs, 1)[0])     # crossing speed [m/s]
        vz = float(np.polyfit(ts, zs, 1)[0])     # negative = approaching
        return vx, -vz

    def drop(self, key):
        self.tracks.pop(key, None)

    def clear(self):
        self.tracks.clear()


# ---------------------------------------------------------------------------
# standalone smoke test (no YOLO): measures the center strip of the frame
# ---------------------------------------------------------------------------
def _main():
    rig = StereoRig()
    print(f"[stereo] standalone test  B={rig.baseline}m vFOV={rig.vfov}deg - "
          "looking for cam_L / cam_R ...")
    last = 0.0
    while True:
        got = rig.grab()
        if got is None:
            if time.time() - last > 3:
                print("[stereo] cam_L / cam_R windows not found")
                last = time.time()
            time.sleep(1.0)
            continue
        imgL, imgR, f_px, cx = got
        H, W = imgL.shape[:2]
        bbox = [W * 0.4, H * 0.25, W * 0.6, H * 0.9]    # center strip
        m = measure_bbox(imgL, imgR, bbox, f_px, cx, rig.baseline)
        if m:
            print(f"[stereo] center-strip Z={m['z']:6.1f}m  "
                  f"disp={m['disparity']:6.2f}px  score={m['score']:.2f}")
        time.sleep(0.5)


if __name__ == "__main__":
    _main()
#==========================detect.py============================================
# -*- coding: utf-8 -*-
"""
detect.py — perception main: YOLO detection + stereo range + cross-verification
================================================================================
Pipeline (per frame):

  1) capture the stereo pair from the UC-win view windows cam_L / cam_R
     (stereo.StereoRig — PrintWindow / screen-region fallback)
  2) YOLO detects pedestrians on the left image (own-trained best.pt:
     classes adult / child; a COCO model falls back to class 'person')
  3) stereo.measure_bbox() turns each box into range / lateral position:
         Z = f*B/disparity,  X = (u-cx)*Z/f,  dist = sqrt(X^2+Z^2)
     and stereo.SpeedTracker turns the track into crossing/closing speed
  4) cross-verification (sensor fusion): each stereo measurement is compared
     against the UC-win telemetry (UDP log + COM ego) — a detection whose
     azimuth AND range agree with a telemetry pedestrian is marked VERIFIED
     and inherits the authoritative class label (child / adult).
     Unverified boxes (e.g. YOLO false positives on tires/poles) are shown
     in yellow and excluded from the decision output.
  5) output:
       - console line per target: class, distance, speed, VERIFIED flag
       - HUD window with colored boxes (adult green / child orange)
       - stereo_person.json (atomic write) for the brake controller contract:
           {timestamp, distance_m, closing_speed_mps, class,
            person_speed_mps, verified, source}
         distance_m = 999999 when there is no forward target.

Ports: brake.py listens on UDP 4000. Run detect.py on a second log host row
(add 127.0.0.1:4001 in the Log Export settings and tick its enable box), or
give --port 4000 if brake.py is not running.

Run:
  python detect.py --model best.pt              (full pipeline)
  python detect.py --no-stereo                  (telemetry-only fallback)
Stop: Ctrl+C  (or q in the HUD window)
"""

import argparse
import json
import math
import os
import time

import pythoncom

import common
import stereo

JSON_PATH = "stereo_person.json"
NO_TARGET = 999999.0
AZ_TOL_DEG = 12.0        # azimuth agreement tolerance for verification
RANGE_TOL = 0.25         # relative range agreement tolerance (25 %)
MIN_AHEAD = 0.5          # forward projection below this = passing by
STALE_SEC = 2.0


def write_json_atomic(payload):
    tmp = JSON_PATH + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(payload, f, ensure_ascii=False)
    os.replace(tmp, JSON_PATH)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--model", default="best.pt",
                    help="YOLO weights (own-trained adult/child model)")
    ap.add_argument("--conf", type=float, default=0.35)
    ap.add_argument("--vfov", type=float, default=stereo.VFOV_DEG_DEFAULT)
    ap.add_argument("--baseline", type=float, default=stereo.BASELINE_DEFAULT)
    ap.add_argument("--child", default=common.CHILD_ID_DEFAULT)
    ap.add_argument("--adult", default=common.ADULT_ID_DEFAULT)
    ap.add_argument("--mirror-c", type=float, default=common.MIRROR_C_DEFAULT)
    ap.add_argument("--port", type=int, default=4001,
                    help="UDP log port for this process (brake.py uses 4000; "
                         "add a second enabled host row 127.0.0.1:4001)")
    ap.add_argument("--no-stereo", action="store_true",
                    help="skip cam windows / YOLO, telemetry-only output")
    ap.add_argument("--no-hud", action="store_true")
    ap.add_argument("--hide-unverified", action="store_true",
                    help="do not draw unverified boxes (clean recording)")
    args = ap.parse_args()

    pythoncom.CoInitialize()

    # --- perception building blocks -------------------------------------
    model = None
    rig = None
    tracker = stereo.SpeedTracker()
    if not args.no_stereo:
        try:
            from ultralytics import YOLO
        except ImportError:
            print("[detect] ultralytics missing: pip install ultralytics")
            return
        import cv2
        if not os.path.exists(args.model):
            print(f"[detect] model '{args.model}' not found - falling back to "
                  "yolov8n.pt (COCO 'person')")
            args.model = "yolov8n.pt"
        model = YOLO(args.model)
        det_classes = [0] if os.path.basename(args.model).startswith(
            ("yolov8", "yolo11n.pt")) else None
        print(f"[detect] YOLO loaded: {args.model}")
        rig = stereo.StereoRig(args.vfov, args.baseline)

    tel = common.Telemetry([args.child, args.adult], port=args.port)
    ego_link = common.EgoLink()
    cls_of = {args.child: "child", args.adult: "adult"}
    label_of = {"child": "Child", "adult": "Adult"}

    sign_flip = [None]     # camera-vs-telemetry azimuth sign (auto-detected)
    warned = None
    t_print = 0.0
    t_json = 0.0

    print(f"[detect] child={args.child} adult={args.adult} "
          f"mirror_c={args.mirror_c} port={args.port}")
    print("[detect] running - Ctrl+C to stop\n")

    try:
        while True:
            tel.poll()
            ego, _car, msg = ego_link.read()
            if ego is None:
                if msg and warned != msg:
                    print(f"[detect] {msg}")
                    warned = msg
                time.sleep(0.3)
                continue
            if warned:
                print("[detect] ego car connected")
                warned = None
            ex, ez, dx, dz, vk = ego
            dn = math.hypot(dx, dz)
            if dn > 1e-6:
                dx, dz = dx / dn, dz / dn
            v_ms = vk / 3.6

            # --- telemetry pedestrians (authoritative geometry) ----------
            peds = {}          # cls -> (dist, ahead, azimuth, speed)
            for oid, cls in cls_of.items():
                r = tel.rel(oid, ex, ez, dx, dz, args.mirror_c)
                if r is not None:
                    peds[cls] = r

            # --- stereo + YOLO ------------------------------------------
            detections = []    # dicts: bbox, yolo_cls, stereo(m), verified, cls
            frame = None
            if rig is not None:
                got = rig.grab()
                if got is not None:
                    imgL, imgR, f_px, cx = got
                    frame = imgL
                    det = model(imgL, classes=det_classes, conf=args.conf,
                                verbose=False)[0]
                    for b in det.boxes:
                        bbox = [float(v) for v in b.xyxy[0]]
                        yolo_cls = det.names.get(int(b.cls[0]), "person")
                        m = stereo.measure_bbox(imgL, imgR, bbox, f_px, cx,
                                                args.baseline)
                        entry = {"bbox": bbox, "yolo_cls": yolo_cls,
                                 "m": m, "verified": False, "cls": yolo_cls}
                        # cross-verification against telemetry
                        if m is not None:
                            best_cls, best_err = None, 1e9
                            for cls, (d, ahead, az_t, _v) in peds.items():
                                if ahead <= MIN_AHEAD:
                                    continue
                                for s in ((sign_flip[0],) if sign_flip[0]
                                          else (1.0, -1.0)):
                                    err = abs(math.degrees(s * m["azimuth"] - az_t))
                                    if err < best_err:
                                        best_err, best_cls, best_s = err, cls, s
                            if best_cls is not None \
                                    and best_err <= AZ_TOL_DEG \
                                    and abs(m["dist"] - peds[best_cls][0]) \
                                        <= RANGE_TOL * peds[best_cls][0] + 3.0:
                                entry["verified"] = True
                                entry["cls"] = best_cls
                                sign_flip[0] = best_s
                                vx, vcl = tracker.update(
                                    best_cls, m["x_lat"], m["z"])
                                entry["crossing"] = vx
                                entry["closing"] = vcl
                        detections.append(entry)

                    # --- HUD --------------------------------------------
                    if not args.no_hud:
                        hud = frame.copy()
                        for e in detections:
                            if args.hide_unverified and not e["verified"]:
                                continue
                            x1, y1, x2, y2 = [int(v) for v in e["bbox"]]
                            if not e["verified"]:
                                col = (0, 230, 230)         # yellow: unverified
                                lab = f"{e['yolo_cls']}?"
                            else:
                                col = ((0, 165, 255) if e["cls"] == "child"
                                       else (0, 220, 0))
                                d_show = peds[e["cls"]][0]
                                lab = f"{e['cls']} {d_show:.1f}m"
                                pv = peds[e["cls"]][3]
                                if pv is not None:
                                    lab += f" {pv:.1f}m/s"
                                lab += " [OK]"
                            cv2.rectangle(hud, (x1, y1), (x2, y2), col, 2)
                            cv2.putText(hud, lab, (x1, max(20, y1 - 8)),
                                        cv2.FONT_HERSHEY_SIMPLEX, 0.6, col, 2)
                        cv2.putText(hud, f"v={vk:.1f}km/h",
                                    (10, 26), cv2.FONT_HERSHEY_SIMPLEX,
                                    0.7, (240, 240, 240), 2)
                        cv2.imshow("PERCEPTION (cam_L)", hud)
                        if cv2.waitKey(1) & 0xFF == ord("q"):
                            break

            # --- decision output (controller contract) -------------------
            fwd = [(d, cls, pv) for cls, (d, ahead, _az, pv) in peds.items()
                   if ahead > MIN_AHEAD]
            fwd.sort()
            if time.time() - t_json >= 0.25:
                t_json = time.time()
                if fwd:
                    d, cls, pv = fwd[0]
                    verified = any(e["verified"] and e["cls"] == cls
                                   for e in detections)
                    write_json_atomic({
                        "timestamp": time.time(),
                        "distance_m": round(d, 2),
                        "closing_speed_mps": round(v_ms, 3),
                        "class": cls,
                        "person_speed_mps": round(pv, 2) if pv else None,
                        "verified": verified,
                        "source": "fusion" if verified else "telemetry"})
                else:
                    write_json_atomic({
                        "timestamp": time.time(),
                        "distance_m": NO_TARGET,
                        "closing_speed_mps": round(v_ms, 3),
                        "class": None, "person_speed_mps": None,
                        "verified": False, "source": "telemetry"})

            # --- console -------------------------------------------------
            if time.time() - t_print >= 0.5:
                t_print = time.time()
                parts = [f"Car {vk:5.1f}km/h"]
                for cls, (d, ahead, _az, pv) in sorted(
                        peds.items(), key=lambda kv: kv[1][0]):
                    ok = any(e["verified"] and e["cls"] == cls
                             for e in detections)
                    side = "fwd" if ahead > MIN_AHEAD else "passed"
                    v_txt = f" {pv:.1f}m/s" if pv is not None else ""
                    parts.append(f"{label_of[cls]} {d:6.1f}m{v_txt} "
                                 f"({side}{', VERIFIED' if ok else ''})")
                n_unv = sum(1 for e in detections if not e["verified"])
                if n_unv:
                    parts.append(f"unverified x{n_unv}")
                print("[dist] " + "  |  ".join(parts))

            time.sleep(0.02)

    except KeyboardInterrupt:
        pass
    finally:
        try:
            write_json_atomic({"timestamp": time.time(),
                               "distance_m": NO_TARGET,
                               "closing_speed_mps": 0.0,
                               "class": None, "person_speed_mps": None,
                               "verified": False, "source": "telemetry"})
        except Exception:
            pass
        tel.close()
        if rig is not None:
            try:
                import cv2
                cv2.destroyAllWindows()
            except Exception:
                pass
        pythoncom.CoUninitialize()
        print("\n[detect] done")


if __name__ == "__main__":
    main()
#==========================brake.py=============================================
# -*- coding: utf-8 -*-
"""
brake.py - Pedestrian AEB (Autonomous Emergency Braking) for UC-win/Road.

Control logic is unchanged from the validated version; the UC-win access
code (COM attach, UDP telemetry) now lives in common.py.

Usage:
    python brake.py                  (default: child=5764, adult=5763)
    python brake.py --actuator dry   (decision log only, no braking)
Stop: Ctrl+C
"""

import argparse
import math
import time

import pythoncom

import common

G = 9.81
DETECT_RANGE = 150.0
STALE_SEC = 2.0
BRAKE_STALE_SEC = 3.0
PED_HALF_WIDTH = 0.3
PASS_ARM_DIST = 30.0
PWM_PERIOD = 0.03
K_P = 0.05
K_I = 0.08
DUTY_I_MAX = 0.6
A_REQ_MIN = 0.4
A_REQ_MAX = 5.0
RESTART_GAP = 5.0
CLOSE_EMA = 0.3
FB_GAIN = 1.5
HOLD_STEP = 0.01
EMERG_CHECK_SEC = 2.0
EMERG_MIN_DECEL = 0.4


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--child", default=common.CHILD_ID_DEFAULT)
    ap.add_argument("--adult", default=common.ADULT_ID_DEFAULT)
    ap.add_argument("--mirror-c", type=float, default=common.MIRROR_C_DEFAULT,
                    help="coordinate mirror constant: z_int = C - z_udp")
    ap.add_argument("--port", type=int, default=4000)
    ap.add_argument("--decel", type=float, default=2.5,
                    help="target deceleration profile [m/s^2]")
    ap.add_argument("--a-pb", type=float, default=6.15,
                    help="measured full parking-brake deceleration [m/s^2]")
    ap.add_argument("--a-push", type=float, default=2.8,
                    help="measured scenario acceleration when released [m/s^2]")
    ap.add_argument("--margin", type=float, default=None,
                    help="override stop margin for ALL classes [m] "
                         "(default: class-aware, adult 8 / child 10)")
    ap.add_argument("--margin-adult", type=float, default=8.0,
                    help="stop margin in front of an adult [m]")
    ap.add_argument("--margin-child", type=float, default=10.0,
                    help="stop margin in front of a child [m] "
                         "(children are less predictable - larger margin)")
    ap.add_argument("--bumper", type=float, default=None,
                    help="reference-to-bumper offset [m] (auto if omitted)")
    ap.add_argument("--latency", type=float, default=0.2,
                    help="sensing-to-actuation latency allowance [s]")
    ap.add_argument("--safety", type=float, default=1.15,
                    help="braking distance safety factor")
    ap.add_argument("--pass-margin", type=float, default=2.0,
                    help="release brake when target recedes this far past its minimum [m]")
    ap.add_argument("--actuator", choices=("pb", "dry"), default="pb")
    args = ap.parse_args()

    dry = args.actuator == "dry"
    decel = args.decel

    # D_STOP_BY_CLASS: class-aware stop line (see manual §4 Key Variables)
    D_STOP_BY_CLASS = {"adult": args.margin_adult, "child": args.margin_child}

    def margin_of(cls):
        if args.margin is not None:
            return args.margin
        return D_STOP_BY_CLASS.get(cls, args.margin_adult)

    pythoncom.CoInitialize()

    tel = common.Telemetry([args.child, args.adult], port=args.port)
    ego_link = common.EgoLink()

    cls_of = {args.child: "child", args.adult: "adult"}
    label_of = {"child": "Child", "adult": "Adult"}
    min_d = {}
    passed = set()

    print(f"[brake] child={args.child}  adult={args.adult}  mirror_c={args.mirror_c}")
    print(f"[brake] decel {decel:.2f} m/s^2 | stop line adult {margin_of('adult')}m / "
          f"child {margin_of('child')}m | safety {args.safety} | "
          f"mode {'DRY' if dry else 'ParkingBrake PWM'}")

    state = "CRUISE"
    brake_oid = None
    brake_t0 = 0.0
    brake_v0 = 0.0
    v_des = 0.0
    v_cmd = 0.0
    duty = 0.5
    duty_i = 0.0
    close_rate = {}
    last_de = {}
    emergency = False
    stopped_said = False
    bumper = args.bumper
    warned = None
    t_print = 0.0
    t_prev = time.time()

    def set_speed(car, v_kmh):
        car.SetSpeed(1, max(0.0, v_kmh))

    try:
        while True:
            now = time.time()
            dt = min(now - t_prev, 0.25)
            t_prev = now

            tel.poll()

            ego, car, msg = ego_link.read()
            if ego is None:
                if msg and warned != msg:
                    print(f"[brake] {msg}")
                    warned = msg
                time.sleep(0.3)
                continue
            if warned:
                print("[brake] driver car connected")
                warned = None

            if bumper is None:
                try:
                    bumper = float(car.FrontLength) + PED_HALF_WIDTH
                except Exception:
                    bumper = 2.0
                print(f"[brake] bumper offset {bumper:.2f}m")

            ex, ez, dx, dz, vk = ego
            dn = math.hypot(dx, dz)
            if dn > 1e-6:
                dx, dz = dx / dn, dz / dn
            v_ms = vk / 3.6

            entries = []
            for oid, cls in cls_of.items():
                r = tel.rel(oid, ex, ez, dx, dz, args.mirror_c)
                if r is None:
                    continue
                d, ahead, _az, _v = r
                if oid in passed or d > DETECT_RANGE:
                    continue
                if oid not in min_d or d < min_d[oid]:
                    min_d[oid] = d
                elif ((min_d[oid] < PASS_ARM_DIST
                       and d > min_d[oid] + args.pass_margin)
                      or ahead < -1.0):
                    passed.add(oid)
                    print(f"[brake] {label_of[cls]} passed (min dist {min_d[oid]:.1f}m)")
                    continue
                entries.append((d - bumper, oid, cls, d, ahead))

            fwd = [e for e in entries if e[4] > 0]
            fwd.sort(key=lambda e: e[0])
            tgt = fwd[0] if fwd else None

            for de, oid, cls, d, ahead in entries:
                if oid in last_de:
                    de0, t0m = last_de[oid]
                    dtm = now - t0m
                    if 0.02 <= dtm <= 1.0:
                        rate = (de0 - de) / dtm
                        if -5.0 <= rate <= 40.0:
                            prev = close_rate.get(oid, v_ms)
                            close_rate[oid] = ((1 - CLOSE_EMA) * prev
                                               + CLOSE_EMA * rate)
                last_de[oid] = (de, now)

            if tgt is not None:
                vc = close_rate.get(tgt[1], v_ms)
                v_ped = max(0.0, vc - v_ms)
                m_stop = margin_of(tgt[2])
            else:
                vc, v_ped = v_ms, 0.0
                m_stop = args.margin_adult
            trigger = (m_stop + max(vc, v_ms) * args.latency
                       + args.safety * (v_ms * v_ms / 2 + v_ped * v_ms) / decel)

            if state == "CRUISE":
                if tgt and tgt[0] <= trigger:
                    state = "BRAKE"
                    brake_oid = tgt[1]
                    brake_t0 = time.time()
                    brake_v0 = vk
                    v_des = vk
                    v_cmd = vk
                    duty = 0.5
                    duty_i = 0.0
                    emergency = False
                    stopped_said = False
                    print(f"[brake] BRAKE: {label_of[tgt[2]]} at {tgt[0]:.1f}m "
                          f"<= trigger {trigger:.1f}m (v={vk:.1f}km/h)")

            elif state == "BRAKE":
                gone = brake_oid in passed
                stale = time.time() - tel.seen.get(brake_oid, 0) > BRAKE_STALE_SEC
                cur = next((e for e in entries if e[1] == brake_oid), None)
                m_b = margin_of(cur[2]) if cur is not None else args.margin_adult
                too_early = (vk < 1.0 and cur is not None
                             and cur[0] > m_b + RESTART_GAP)
                if gone or stale or too_early:
                    state = "CRUISE"
                    brake_oid = None
                    if not dry:
                        try:
                            car.ParkingBrake = False
                        except Exception:
                            pass
                    if too_early:
                        print(f"[brake] stopped {cur[0]:.1f}m short - "
                              "released to re-approach")
                    else:
                        print("[brake] "
                              + ("target passed" if gone else "target lost")
                              + " - brake released")
                else:
                    v_ped_b = max(0.0, close_rate.get(brake_oid, v_ms) - v_ms)
                    if cur is not None and v_ms > 0.3:
                        d_rem = cur[0] - m_b
                        a_des = ((v_ms * v_ms / 2 + v_ped_b * v_ms) / d_rem
                                 if d_rem > 0.05 else A_REQ_MAX)
                        a_des = min(max(a_des, A_REQ_MIN), A_REQ_MAX)
                    else:
                        a_des = decel
                    v_des = max(0.0, v_des - a_des * 3.6 * dt)
                    err = vk - v_des
                    duty_i = min(DUTY_I_MAX, max(-0.3, duty_i + K_I * err * dt))
                    duty = ((a_des + args.a_push) / (args.a_pb + args.a_push)
                            + K_P * err + duty_i)
                    duty = min(1.0, max(0.0, duty))
                    v_cmd = max(0.0, v_cmd - decel * 3.6 * dt)
                    if not emergency and time.time() - brake_t0 > EMERG_CHECK_SEC:
                        meas = ((brake_v0 - vk) / 3.6
                                / (time.time() - brake_t0))
                        if meas < EMERG_MIN_DECEL and vk > 5.0:
                            emergency = True
                            print(f"[brake] WARNING: low deceleration "
                                  f"({meas:.2f} m/s^2) - emergency mode")
                    if vk < 1.0 and not stopped_said:
                        stopped_said = True
                        if cur:
                            print(f"[brake] STOPPED - {cur[0]:.2f}m to pedestrian "
                                  f"({cur[2]}: target margin {m_b}m)")
                        else:
                            print("[brake] STOPPED")

            if time.time() - t_print >= 0.5:
                t_print = time.time()
                parts = [f"{state:6s} v {vk:5.1f}km/h trig {trigger:5.1f}m"]
                if state == "BRAKE" and not emergency:
                    parts[0] += f" duty {duty:4.2f}"
                for de, oid, cls, d, ahead in sorted(entries, key=lambda e: e[0]):
                    mark = "*" if (tgt and oid == tgt[1]) else " "
                    parts.append(f"{mark}{label_of[cls]} {de:6.1f}m")
                print("[dist] " + "  |  ".join(parts))

            if not dry and state == "BRAKE" and car is not None:
                try:
                    if emergency:
                        t_end = time.time() + 0.05
                        while time.time() < t_end:
                            set_speed(car, v_cmd)
                            time.sleep(HOLD_STEP)
                    else:
                        car.Throttle = 0.0
                        if vk < 1.0 or duty >= 0.97:
                            car.ParkingBrake = True
                            time.sleep(PWM_PERIOD)
                        elif duty <= 0.03:
                            car.ParkingBrake = False
                            time.sleep(PWM_PERIOD)
                        else:
                            car.ParkingBrake = True
                            time.sleep(PWM_PERIOD * duty)
                            car.ParkingBrake = False
                            time.sleep(PWM_PERIOD * (1.0 - duty))
                except Exception:
                    time.sleep(0.05)
            else:
                time.sleep(0.05)

    except KeyboardInterrupt:
        pass
    finally:
        try:
            if ego_link.holder[0] is not None:
                c = ego_link.holder[0].SimulationCore.TrafficSimulation.Driver.CurrentCar
                if c is not None:
                    c.ParkingBrake = False
        except Exception:
            pass
        tel.close()
        pythoncom.CoUninitialize()
        print("\n[brake] exit (parking brake released)")


if __name__ == "__main__":
    main()
