#!/usr/bin/env python3
"""chandra-camera: mobile Wayland camera app for Chandra using libcamera / V4L2."""

import argparse
from dataclasses import dataclass
import datetime
import fcntl
import glob
import mmap
import os
import queue
import shutil
import signal
import struct
import subprocess
import sys
import threading
import time

os.environ.setdefault("LIBCAMERA_LOG_LEVELS", "*:ERROR")

APP_ID = "chandra-camera"
APP_TITLE = "Camera"
PICTURE_DIR = os.path.expanduser("~/Pictures/Camera")
VIDEO_DIR = os.path.expanduser("~/Videos/Camera")
FLASH_LED_PATH = "/sys/class/leds/white:flash/brightness"
IMAGE_EXTS = (".jpg", ".jpeg", ".png", ".webp")
VIDEO_EXTS = (".mp4", ".mkv", ".webm")

QUAD_BAYER_MODELS = {"imx371"}

# Fallback resolutions when a camera reports no enumerated StillCapture sizes.
DEFAULT_VIEWFINDER_SIZE = (1280, 960)
PREFERRED_STILL_SIZES = [
    (4648, 3496),
    (3840, 2160),
    (2584, 1940),
    (2320, 1740),
    (1920, 1440),
    (1280, 960),
]


@dataclass
class CameraInfo:
    """Descriptor for one discovered libcamera or V4L2 camera."""

    cid: str
    backend: str  # "libcamera" or "v4l2"
    model: str
    location: int  # 0=Front, 1=Back, 2=External
    rotation: int
    label: str
    max_pixels: int = 0

    @property
    def is_front(self):
        return self.location == 0

    @property
    def is_back(self):
        return self.location == 1


def _import_libcamera():
    """Import libcamera after silencing non-error C++ log noise."""
    os.environ.setdefault("LIBCAMERA_LOG_LEVELS", "*:ERROR")
    import libcamera
    return libcamera


def _short_model_name(raw_model, fallback_id):
    """Turn a libcamera Model property or device path into a compact sensor label."""
    if raw_model:
        s = str(raw_model).strip()
        if "/" in s:
            s = s.rsplit("/", 1)[-1]
        if s:
            return s
    tail = fallback_id.rsplit("/", 1)[-1]
    return tail or fallback_id


def sort_and_label_cameras(raw_items):
    """Sort cameras (primary Back first, then Front, then extra Back/External) and assign unique labels.

    Each item in raw_items is a tuple:
      (cid, backend, model, location, rotation, max_pixels)
    """
    loc_word = {0: "Front", 1: "Back", 2: "External"}

    back_items = [it for it in raw_items if it[3] == 1]
    primary_back_cid = None
    if back_items:
        best_back = min(
            back_items,
            key=lambda it: (0 if "imx519" in it[2].lower() else 1, -it[5], it[0]),
        )
        primary_back_cid = best_back[0]

    def sort_key(item):
        cid, _backend, model, loc, _rot, max_px = item
        if loc == 1:
            group = 0 if cid == primary_back_cid else 2
        elif loc == 0:
            group = 1
        else:
            group = 3
        return (group, -max_px, cid)

    ordered = sorted(raw_items, key=sort_key)
    counts_by_loc = {}
    for item in ordered:
        loc = item[3]
        counts_by_loc[loc] = counts_by_loc.get(loc, 0) + 1

    seen_by_loc = {}
    out = []
    for cid, backend, model, loc, rot, max_px in ordered:
        idx = seen_by_loc.get(loc, 0) + 1
        seen_by_loc[loc] = idx
        prefix = loc_word.get(loc, "Camera")
        if counts_by_loc.get(loc, 0) > 1 and idx > 1:
            tag = "%s %d" % (prefix, idx)
        else:
            tag = prefix
        short = _short_model_name(model, cid)
        label = "%s · %s" % (tag, short) if short else tag
        out.append(
            CameraInfo(
                cid=cid,
                backend=backend,
                model=short,
                location=loc,
                rotation=int(rot or 0),
                label=label,
                max_pixels=int(max_px or 0),
            )
        )
    return out


def discover_cameras():
    """Return sorted CameraInfo list from libcamera, falling back to V4L2."""
    raw = []
    try:
        libcamera = _import_libcamera()
        cm = libcamera.CameraManager.singleton()
        for cam in cm.cameras:
            props = cam.properties
            loc = props.get(libcamera.properties.Location)
            if loc is None:
                loc = 2
            rot = props.get(libcamera.properties.Rotation) or 0
            model = str(props.get(libcamera.properties.Model) or _short_model_name("", cam.id))
            max_px = 0
            try:
                pa = props.get(libcamera.properties.PixelArraySize)
                if pa is not None:
                    max_px = int(pa.width) * int(pa.height)
            except Exception:
                max_px = 0
            raw.append((cam.id, "libcamera", model, int(loc), int(rot), max_px))
    except ImportError:
        raw = []
    except Exception:
        raw = []

    if raw:
        return sort_and_label_cameras(raw)

    # V4L2 fallback for desktops without libcamera sensors.
    import glob
    v4l2 = []
    for idx in range(10):
        path = "/dev/video%d" % idx
        if not os.path.exists(path):
            continue
        sys_name = "/sys/class/video4linux/video%d/name" % idx
        name = "Camera %d" % idx
        if os.path.exists(sys_name):
            try:
                name = open(sys_name).read().strip() or name
            except OSError:
                pass
        if "metadata" in name.lower() or "decoder" in name.lower() or "encoder" in name.lower():
            continue
        v4l2.append((path, "v4l2", name, 2, 0, 0))
    if not v4l2:
        for path in sorted(glob.glob("/dev/v4l/by-id/*-video-index0")):
            v4l2.append((path, "v4l2", os.path.basename(path), 2, 0, 0))
    return sort_and_label_cameras(v4l2)


def select_initial_camera(cameras, spec):
    """Pick camera index matching `--camera` spec ('back', 'front', index, or substring)."""
    if not cameras:
        return 0
    if not spec:
        return 0
    q = spec.strip().lower()
    if q.isdigit():
        idx = int(q)
        if 0 <= idx < len(cameras):
            return idx
    if q in ("back", "rear"):
        for i, c in enumerate(cameras):
            if c.is_back:
                return i
    if q in ("front", "selfie"):
        for i, c in enumerate(cameras):
            if c.is_front:
                return i
    for i, c in enumerate(cameras):
        if q in c.cid.lower() or q in c.model.lower() or q in c.label.lower():
            return i
    return 0


def rotate_bgr(bgr, rot, cv2_mod):
    """Rotate BGR frame according to libcamera.properties.Rotation (CCW mounting angle)."""
    rot_i = int(rot) % 360
    if rot_i == 90:
        return cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_COUNTERCLOCKWISE)
    if rot_i == 180:
        return cv2_mod.rotate(bgr, cv2_mod.ROTATE_180)
    if rot_i == 270:
        return cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_CLOCKWISE)
    return bgr


def convert_frame(raw, width, height, stride, fmt, rot=0, cv2_mod=None, np_mod=None):
    """Convert raw camera buffer bytes into a contiguous upright uint8 BGR image."""
    if np_mod is None:
        import numpy as np_mod
    if cv2_mod is None:
        import cv2 as cv2_mod

    arr = np_mod.frombuffer(raw, dtype=np_mod.uint8)
    fmt_u = str(fmt).upper()
    if fmt_u in ("ABGR8888", "XBGR8888", "ARGB8888", "XRGB8888"):
        row_px = stride // 4
        img = arr[:height * stride].reshape((height, row_px, 4))[:, :width, :3]
        if "BGR" in fmt_u:
            bgr = np_mod.ascontiguousarray(img[:, :, ::-1])
        else:
            bgr = np_mod.ascontiguousarray(img)
    elif fmt_u in ("RGB888", "BGR888"):
        row_px = stride // 3
        img = arr[:height * stride].reshape((height, row_px, 3))[:, :width, :]
        if fmt_u == "RGB888":
            bgr = np_mod.ascontiguousarray(img[:, :, ::-1])
        else:
            bgr = np_mod.ascontiguousarray(img)
    else:
        raise RuntimeError("unsupported pixel format %s" % fmt)

    return np_mod.ascontiguousarray(rotate_bgr(bgr, rot, cv2_mod))


VIDIOC_G_CTRL = 0xC008561B
VIDIOC_S_CTRL = 0xC008561C
VIDIOC_QUERYCTRL = 0xC0445624
V4L2_CID_EXPOSURE = 0x00980911
V4L2_CID_VBLANK = 0x009E0901
V4L2_CID_ANALOGUE_GAIN = 0x009E0903
V4L2_CID_DIGITAL_GAIN = 0x009F0905

_QUAD_TONE_LUT = None


def _build_tone_lut(np_mod):
    """Build 4096-entry uint8 tone LUT: linear 0..160, smooth highlight roll-off to 768, gamma 2.2."""
    x = np_mod.linspace(0.0, 768.0, 4096, dtype=np_mod.float32)
    t = np_mod.maximum(x - 160.0, 0.0) / 95.0
    y = np_mod.where(x <= 160.0, x, 160.0 + 95.0 * (t / (1.0 + 0.65 * t)))
    y = np_mod.clip(y / 255.0, 0.0, 1.0)
    return np_mod.clip((y ** (1.0 / 2.2)) * 255.0, 0, 255).astype(np_mod.uint8)


def _get_tone_lut(np_mod):
    global _QUAD_TONE_LUT
    if _QUAD_TONE_LUT is None:
        _QUAD_TONE_LUT = _build_tone_lut(np_mod)
    return _QUAD_TONE_LUT


def find_sensor_subdev(model):
    """Find /dev/v4l-subdevN matching sensor `model`, or None."""
    if not model:
        return None
    want = model.lower()
    for p in sorted(glob.glob("/sys/class/video4linux/v4l-subdev*/name")):
        try:
            with open(p) as fh:
                name = fh.read().strip().lower()
        except OSError:
            continue
        if name == want or name.startswith(want + " "):
            return "/dev/" + os.path.basename(os.path.dirname(p))
    return None


class _V4L2SubdevIO:
    """Thin ioctl wrapper over a V4L2 subdevice file descriptor."""

    def __init__(self, path):
        self.fd = os.open(path, os.O_RDWR)

    def query(self, cid):
        buf = bytearray(68)
        struct.pack_into("<I", buf, 0, cid)
        fcntl.ioctl(self.fd, VIDIOC_QUERYCTRL, buf)
        mn, mx, step, df, _flags = struct.unpack_from("<iiiiI", buf, 40)
        return mn, mx, step, df

    def get(self, cid):
        buf = bytearray(8)
        struct.pack_into("<Ii", buf, 0, cid, 0)
        fcntl.ioctl(self.fd, VIDIOC_G_CTRL, buf)
        return struct.unpack_from("<Ii", buf, 0)[1]

    def set(self, cid, val):
        buf = bytearray(8)
        struct.pack_into("<Ii", buf, 0, cid, int(val))
        fcntl.ioctl(self.fd, VIDIOC_S_CTRL, buf)
        return struct.unpack_from("<Ii", buf, 0)[1]

    def close(self):
        if self.fd >= 0:
            try:
                os.close(self.fd)
            finally:
                self.fd = -1


class QuadSensorAE:
    """Direct V4L2 subdev auto-exposure and gain controller for Raw-only Quad-Bayer capture."""

    def __init__(self, subdev_path, io=None):
        self.io = io if io is not None else _V4L2SubdevIO(subdev_path)
        self._closed = False
        try:
            self.vb_min, self.vb_max, _, _ = self.io.query(V4L2_CID_VBLANK)
            self.exp_min, self.exp_max_now, _, _ = self.io.query(V4L2_CID_EXPOSURE)
            self.ag_min, self.ag_max, _, _ = self.io.query(V4L2_CID_ANALOGUE_GAIN)
            self.init_vblank = self.io.get(V4L2_CID_VBLANK)
            self.init_exp = self.io.get(V4L2_CID_EXPOSURE)
            self.init_ag = self.io.get(V4L2_CID_ANALOGUE_GAIN)
            try:
                self.dg_min, self.dg_max, _, _ = self.io.query(V4L2_CID_DIGITAL_GAIN)
                self.init_dg = self.io.get(V4L2_CID_DIGITAL_GAIN)
                self.has_dgain = True
            except OSError:
                self.dg_min, self.dg_max, self.init_dg, self.has_dgain = 1024, 1024, 1024, False
        except Exception:
            self.io.close()
            raise

        self.exp_base_max = max(self.exp_min + 1, self.exp_max_now - max(0, self.init_vblank - self.vb_min))
        self.vb_cap = min(self.vb_max, 9500)
        self.exp_lowlight_max = min(self.exp_base_max + max(0, self.vb_cap - self.vb_min), 12000)
        self.ag_max_x = 512.0 / max(512 - min(self.ag_max, 504), 1)
        self.dg_max_x = min(self.dg_max / 1024.0, 4.0) if self.has_dgain else 1.0
        self.e_min = float(max(20, self.exp_min))
        self.e_max = float(self.exp_lowlight_max) * self.ag_max_x * self.dg_max_x
        self.cur_vblank = self.init_vblank
        self.cur_exp = self.init_exp
        self.cur_ag = self.init_ag
        self.cur_dg = self.init_dg
        self.ev_total = float(self.exp_base_max) * min(8.0, self.ag_max_x)
        self.cooldown = 0

    def plan(self, ev_total):
        """Map scalar exposure target E = exp * ag_x * dg_x to (vblank, exp, ag_code, dg_code)."""
        ev = max(self.e_min, min(float(ev_total), self.e_max))
        mid_ag = min(8.0, self.ag_max_x)
        if ev <= self.exp_base_max:
            exp, ag_x, dg_x, vb = int(round(ev)), 1.0, 1.0, self.vb_min
        elif ev <= self.exp_base_max * mid_ag:
            exp = self.exp_base_max
            ag_x = ev / max(exp, 1)
            dg_x, vb = 1.0, self.vb_min
        elif ev <= self.exp_lowlight_max * mid_ag:
            ag_x = mid_ag
            exp = int(round(ev / ag_x))
            dg_x = 1.0
            vb = self.vb_min + max(0, exp - self.exp_base_max) + (16 if exp > self.exp_base_max else 0)
        elif ev <= self.exp_lowlight_max * self.ag_max_x:
            exp = self.exp_lowlight_max
            vb = self.vb_min + max(0, exp - self.exp_base_max) + (16 if exp > self.exp_base_max else 0)
            ag_x = ev / max(exp, 1)
            dg_x = 1.0
        else:
            exp = self.exp_lowlight_max
            vb = self.vb_min + max(0, exp - self.exp_base_max) + (16 if exp > self.exp_base_max else 0)
            ag_x = self.ag_max_x
            dg_x = ev / max(exp * ag_x, 1.0)

        vb = max(self.vb_min, min(vb, self.vb_cap))
        exp = max(self.exp_min, min(exp, self.exp_lowlight_max))
        ag_code = int(round(512.0 * (1.0 - 1.0 / max(ag_x, 1.0))))
        ag_code = max(self.ag_min, min(ag_code, self.ag_max))
        dg_code = int(round(1024.0 * max(dg_x, 1.0))) if self.has_dgain else 1024
        if self.has_dgain:
            dg_code = max(min(1024, self.dg_max), min(dg_code, self.dg_max))
        return vb, exp, ag_code, dg_code

    def _apply_exp_vblank(self, vb, exp):
        """Enforce sensor ordering: raise VBLANK before raising EXPOSURE; shrink EXPOSURE before shrinking VBLANK."""
        if vb > self.cur_vblank:
            self.io.set(V4L2_CID_VBLANK, vb)
            self.io.set(V4L2_CID_EXPOSURE, exp)
        elif vb < self.cur_vblank:
            self.io.set(V4L2_CID_EXPOSURE, exp)
            self.io.set(V4L2_CID_VBLANK, vb)
        else:
            self.io.set(V4L2_CID_EXPOSURE, exp)

    def _apply(self, vb, exp, ag_code, dg_code):
        self._apply_exp_vblank(vb, exp)
        self.io.set(V4L2_CID_ANALOGUE_GAIN, ag_code)
        if self.has_dgain:
            self.io.set(V4L2_CID_DIGITAL_GAIN, dg_code)
        self.cur_vblank, self.cur_exp, self.cur_ag, self.cur_dg = vb, exp, ag_code, dg_code

    def apply_initial(self):
        self.ev_total = float(self.exp_base_max) * min(8.0, self.ag_max_x)
        vb, exp, ag, dg = self.plan(self.ev_total)
        self._apply(vb, exp, ag, dg)
        self.cooldown = 2

    def update(self, raw_p50, raw_p95):
        """Adjust exposure/gain from raw 0..255 luma stats with 2-frame pipeline settling cooldown."""
        if self.cooldown > 0:
            self.cooldown -= 1
            return False
        if 36.0 <= raw_p50 <= 64.0 and raw_p95 <= 235.0:
            return False
        ratio = min(4.0, max(0.25, 48.0 / max(raw_p50, 0.5)))
        if raw_p95 > 240.0:
            ratio = min(ratio, max(0.25, 200.0 / max(raw_p95, 1.0)))
        elif raw_p95 > 120.0 and raw_p95 * ratio > 235.0:
            ratio = max(0.25, min(ratio, 235.0 / raw_p95))
        new_ev = max(self.e_min, min(self.ev_total * (ratio ** 0.75), self.e_max))
        if abs(new_ev - self.ev_total) <= self.ev_total * 0.05:
            return False
        vb, exp, ag, dg = self.plan(new_ev)
        self.ev_total = new_ev
        if (vb, exp, ag, dg) != (self.cur_vblank, self.cur_exp, self.cur_ag, self.cur_dg):
            self._apply(vb, exp, ag, dg)
            self.cooldown = 2
            return True
        return False

    def close(self):
        if self._closed:
            return
        self._closed = True
        try:
            if self.has_dgain:
                try:
                    self.io.set(V4L2_CID_DIGITAL_GAIN, self.init_dg)
                except Exception:
                    pass
            try:
                self.io.set(V4L2_CID_ANALOGUE_GAIN, self.init_ag)
            except Exception:
                pass
            try:
                self._apply_exp_vblank(self.init_vblank, self.init_exp)
            except Exception:
                pass
        finally:
            self.io.close()


def debayer_quad_csi2p(
    raw_buf,
    width,
    height,
    stride,
    rot=0,
    offset=0,
    target_size=(960, 720),
    high_quality=False,
    gamma_lut=None,
    tone_lut=None,
    return_stats=False,
    cv2_mod=None,
    np_mod=None,
):
    """Debayer 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB via 2x2 binning into upright BGR uint8."""
    if np_mod is None:
        import numpy as np_mod
    if cv2_mod is None:
        import cv2 as cv2_mod

    arr = np_mod.frombuffer(raw_buf, dtype=np_mod.uint8, count=height * stride, offset=offset).reshape((height, stride))
    even_h = (height // 2) * 2
    even_w = (width // 4) * 4
    row_bytes = (even_w // 4) * 5
    b5 = arr[:even_h, :row_bytes].reshape((even_h // 2, 2, even_w // 4, 5))

    if high_quality:
        lo = b5[:, :, :, 4]
        g0_hi = (
            b5[:, 0, :, 0].astype(np_mod.uint16)
            + b5[:, 0, :, 1]
            + b5[:, 1, :, 0]
            + b5[:, 1, :, 1]
        ) << 2
        g0_lo = (
            (lo[:, 0, :] & 3).astype(np_mod.uint16)
            + ((lo[:, 0, :] >> 2) & 3)
            + (lo[:, 1, :] & 3)
            + ((lo[:, 1, :] >> 2) & 3)
        )
        g1_hi = (
            b5[:, 0, :, 2].astype(np_mod.uint16)
            + b5[:, 0, :, 3]
            + b5[:, 1, :, 2]
            + b5[:, 1, :, 3]
        ) << 2
        g1_lo = (
            ((lo[:, 0, :] >> 4) & 3).astype(np_mod.uint16)
            + ((lo[:, 0, :] >> 6) & 3)
            + ((lo[:, 1, :] >> 4) & 3)
            + ((lo[:, 1, :] >> 6) & 3)
        )
        bayer = np_mod.empty((even_h // 2, even_w // 2), dtype=np_mod.uint16)
        bayer[:, 0::2] = g0_hi + g0_lo
        bayer[:, 1::2] = g1_hi + g1_lo
        max_val = 4092.0
        black_cap = 256.0
    else:
        p8 = b5[:, :, :, :4]
        s = p8[:, 0, :, :].astype(np_mod.uint16)
        s += p8[:, 1, :, :]
        bayer = np_mod.ascontiguousarray((s[:, :, 0::2] + s[:, :, 1::2]).reshape((even_h // 2, even_w // 2)))
        max_val = 1020.0
        black_cap = 64.0

    bgr16 = cv2_mod.cvtColor(bayer, cv2_mod.COLOR_BayerBG2BGR)
    if target_size is not None:
        bgr16 = cv2_mod.resize(bgr16, target_size, interpolation=cv2_mod.INTER_AREA)

    f = bgr16.astype(np_mod.float32)
    fh, fw = f.shape[:2]
    sub_raw = f[8:-8:4, 8:-8:4] if (fh > 32 and fw > 32) else f
    black = float(np_mod.clip(np_mod.percentile(sub_raw, 1), 0.0, black_cap))
    f = np_mod.maximum(f - black, 0.0) * (255.0 / max(max_val - black, 1.0))

    sub = f[::4, ::4] if (fh >= 32 and fw >= 32) else f
    means = sub.mean(axis=(0, 1))
    avg = float(means.mean())
    raw_luma = sub.mean(axis=2)
    raw_p50 = float(np_mod.percentile(raw_luma, 50))
    raw_p95 = float(np_mod.percentile(raw_luma, 95))

    if avg > 0.25:
        gains = np_mod.clip(avg / np_mod.maximum(means, max(avg * 0.4, 0.25)), 0.7, 2.0)
    else:
        gains = np_mod.ones(3, dtype=np_mod.float32)

    if raw_p95 < 0.8 and avg < 0.35:
        boost = 1.0
    else:
        boost = float(np_mod.clip(52.0 / max(raw_p50, avg, 0.25), 1.0, 20.0))
        if raw_p95 * boost > 240.0:
            boost = max(1.0, min(boost, 300.0 / max(raw_p95, 1.0)))

    if tone_lut is None:
        tone_lut = _get_tone_lut(np_mod)
    idx = np_mod.clip((f * (gains * boost) * (4095.0 / 768.0)).astype(np_mod.int32), 0, 4095)
    out = tone_lut[idx]

    if boost > 1.8 and out.shape[0] >= 64 and out.shape[1] >= 64:
        lab = cv2_mod.cvtColor(out, cv2_mod.COLOR_BGR2LAB)
        l_ch, a_ch, b_ch = cv2_mod.split(lab)
        l_ch = cv2_mod.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(l_ch)
        a_ch = cv2_mod.GaussianBlur(a_ch, (5, 5), 0)
        b_ch = cv2_mod.GaussianBlur(b_ch, (5, 5), 0)
        out = cv2_mod.cvtColor(cv2_mod.merge([l_ch, a_ch, b_ch]), cv2_mod.COLOR_LAB2BGR)

    res = np_mod.ascontiguousarray(rotate_bgr(out, rot, cv2_mod))
    if return_stats:
        return res, (raw_p50, raw_p95)
    return res


def bgr_to_cairo_argb32(bgr, np_mod=None):
    """Convert contiguous (H, W, 3) uint8 BGR frame into (H, W, 4) BGRA for Cairo FORMAT_RGB24."""
    if np_mod is None:
        import numpy as np_mod
    h, w, _ = bgr.shape
    buf = np_mod.empty((h, w, 4), dtype=np_mod.uint8)
    buf[:, :, :3] = bgr
    buf[:, :, 3] = 255
    return np_mod.ascontiguousarray(buf)


def set_flash_led(on, brightness=96):
    """Toggle the rear white torch LED via logind SetBrightness (fallback to sysfs)."""
    if not os.path.exists(FLASH_LED_PATH):
        return False
    val = int(brightness) if on else 0
    if val < 0:
        val = 0
    if val > 255:
        val = 255

    # Prefer direct sysfs write when permitted, else logind session D-Bus helper.
    try:
        with open(FLASH_LED_PATH, "w") as f:
            f.write(str(val))
        return True
    except OSError:
        pass

    sid = os.environ.get("XDG_SESSION_ID", "").strip()
    if not sid:
        try:
            r = subprocess.run(
                ["loginctl", "list-sessions", "--no-legend"],
                capture_output=True,
                text=True,
                timeout=2,
                check=False,
            )
            uid_s = str(os.getuid())
            for line in r.stdout.splitlines():
                parts = line.split()
                if len(parts) >= 2 and parts[1] == uid_s:
                    sid = parts[0]
                    break
        except Exception:
            sid = ""
    if not sid:
        sid = "auto"

    try:
        r = subprocess.run(
            [
                "busctl",
                "call",
                "org.freedesktop.login1",
                "/org/freedesktop/login1/session/" + sid,
                "org.freedesktop.login1.Session",
                "SetBrightness",
                "ssu",
                "leds",
                "white:flash",
                str(val),
            ],
            capture_output=True,
            text=True,
            timeout=3,
            check=False,
        )
        return r.returncode == 0
    except Exception:
        return False


def ensure_even_frame(bgr):
    """Crop at most 1 pixel from bottom/right edge so width and height are even for H.264."""
    h, w = bgr.shape[:2]
    ew = w & ~1
    eh = h & ~1
    if ew == w and eh == h:
        return bgr
    return bgr[:eh, :ew]


class CameraEngine:
    """Thread-safe libcamera/V4L2 streaming, photo capture, and H.264 recording engine."""

    def __init__(self, cameras, initial_index=0, on_frame=None, on_error=None, on_camera_changed=None):
        import cv2
        import numpy as np

        self.cv2 = cv2
        self.np = np
        self.libcamera = None
        self.cm = None
        self.cameras = cameras
        self.active_index = initial_index if cameras else -1
        self.on_frame = on_frame
        self.on_error = on_error
        self.on_camera_changed = on_camera_changed

        self._lock = threading.Lock()
        self._stop_event = threading.Event()
        self._thread = None

        self._cam = None
        self._sc = None
        self._raw_sc = None
        self._alloc = None
        self._requests = []
        self._v4l2 = None
        self._ae = None
        self._started = False
        self._reuse_arg = None
        self._tone_lut = _build_tone_lut(np)

        self._latest_bgr = None
        self._latest_seq = 0
        self._want_switch = None
        self._still_request = None
        self._still_done = threading.Event()
        self._still_result = (None, None)

        self._rec_lock = threading.Lock()
        self._rec_proc = None
        self._rec_queue = None
        self._rec_thread = None
        self._rec_path = None
        self._rec_start_mono = 0.0
        self._rec_frames = 0
        self._rec_size = None

    @property
    def active_camera(self):
        if 0 <= self.active_index < len(self.cameras):
            return self.cameras[self.active_index]
        return None

    def latest_frame(self):
        with self._lock:
            return self._latest_bgr, self._latest_seq

    def is_recording(self):
        with self._rec_lock:
            return self._rec_proc is not None

    def recording_elapsed(self):
        with self._rec_lock:
            if self._rec_proc is None:
                return 0.0
            return max(0.0, time.monotonic() - self._rec_start_mono)

    def start(self):
        if self._thread is not None or not self.cameras:
            return
        self._stop_event.clear()
        self._thread = threading.Thread(target=self._run_loop, name="chandra-cam-worker", daemon=True)
        self._thread.start()

    def stop(self):
        self.stop_video()
        self._stop_event.set()
        if self._thread is not None:
            self._thread.join(timeout=6.0)
            self._thread = None
        set_flash_led(False)

    def switch_camera(self, index):
        if not self.cameras:
            return
        target = index % len(self.cameras)
        self.stop_video()
        if self.cameras[target].is_front:
            set_flash_led(False)
        with self._lock:
            self._want_switch = target

    def cycle_camera(self):
        if len(self.cameras) <= 1:
            return
        self.switch_camera((self.active_index + 1) % len(self.cameras))

    def _requeue(self, req):
        if self._reuse_arg is not None:
            try:
                req.reuse(self._reuse_arg)
            except TypeError:
                self._reuse_arg = None
                req.reuse()
        else:
            req.reuse()
        self._cam.queue_request(req)

    def _open_camera(self, info, role_name="viewfinder", target_sizes=None):
        if info.backend == "v4l2":
            dev = int(info.cid) if info.cid.isdigit() else info.cid
            cap = self.cv2.VideoCapture(dev, self.cv2.CAP_V4L2)
            if not cap.isOpened():
                cap = self.cv2.VideoCapture(dev)
            if not cap.isOpened():
                raise RuntimeError("failed to open V4L2 camera %s" % info.cid)
            cap.set(self.cv2.CAP_PROP_FRAME_WIDTH, 1280)
            cap.set(self.cv2.CAP_PROP_FRAME_HEIGHT, 960)
            self._v4l2 = cap
            return

        libcamera = _import_libcamera()
        self.libcamera = libcamera
        self.cm = libcamera.CameraManager.singleton()
        reuse_enum = getattr(libcamera.Request, "Reuse", None) or getattr(libcamera.Request, "ReuseFlag", None)
        self._reuse_arg = getattr(reuse_enum, "ReuseBuffers", None) if reuse_enum is not None else None

        cam = self.cm.get(info.cid)
        if cam is None:
            raise RuntimeError("camera %s disappeared" % info.cid)
        cam.acquire()
        self._cam = cam
        try:
            self._sc = None
            self._raw_sc = None
            configured = False
            if role_name == "viewfinder" and info.model.lower() in QUAD_BAYER_MODELS:
                subdev = find_sensor_subdev(info.model)
                if subdev:
                    ae = None
                    try:
                        ae = QuadSensorAE(subdev)
                        cfg = cam.generate_configuration([libcamera.StreamRole.Raw])
                        if cfg is not None and len(cfg) >= 1:
                            cfg.validate()
                            cam.configure(cfg)
                            self._raw_sc = cfg.at(0)
                            self._sc = None
                            self._ae = ae
                            configured = True
                    except Exception:
                        if ae is not None:
                            ae.close()
                        self._ae = None
                        self._raw_sc = None

                if not configured:
                    try:
                        cfg = cam.generate_configuration([
                            libcamera.StreamRole.Viewfinder,
                            libcamera.StreamRole.Raw,
                        ])
                        if cfg is not None and len(cfg) >= 2:
                            cfg.at(0).size = libcamera.Size(640, 480)
                            cfg.validate()
                            cam.configure(cfg)
                            self._sc = cfg.at(0)
                            self._raw_sc = cfg.at(1)
                            configured = True
                    except Exception:
                        self._raw_sc = None

            if not configured:
                role = libcamera.StreamRole.StillCapture if role_name == "still" else libcamera.StreamRole.Viewfinder
                sizes = target_sizes or ([DEFAULT_VIEWFINDER_SIZE] if role_name == "viewfinder" else PREFERRED_STILL_SIZES)
                chosen_exc = None
                for w, h in sizes:
                    try:
                        cfg = cam.generate_configuration([role])
                        sc = cfg.at(0)
                        sc.size = libcamera.Size(w, h)
                        cfg.validate()
                        cam.configure(cfg)
                        self._sc = sc
                        configured = True
                        break
                    except Exception as exc:
                        chosen_exc = exc
                if not configured:
                    raise RuntimeError("failed to configure %s: %s" % (info.label, chosen_exc))

            alloc = libcamera.FrameBufferAllocator(cam)
            self._alloc = alloc
            reqs = []
            if self._sc is not None and self._raw_sc is not None:
                if alloc.allocate(self._sc.stream) <= 0 or alloc.allocate(self._raw_sc.stream) <= 0:
                    raise RuntimeError("failed to allocate camera buffers for %s" % info.label)
                for b0, b1 in zip(alloc.buffers(self._sc.stream), alloc.buffers(self._raw_sc.stream)):
                    r = cam.create_request()
                    r.add_buffer(self._sc.stream, b0)
                    r.add_buffer(self._raw_sc.stream, b1)
                    reqs.append(r)
            elif self._raw_sc is not None:
                if alloc.allocate(self._raw_sc.stream) <= 0:
                    raise RuntimeError("failed to allocate raw buffers for %s" % info.label)
                for b in alloc.buffers(self._raw_sc.stream):
                    r = cam.create_request()
                    r.add_buffer(self._raw_sc.stream, b)
                    reqs.append(r)
            else:
                if alloc.allocate(self._sc.stream) <= 0:
                    raise RuntimeError("failed to allocate camera buffers for %s" % info.label)
                for buf in alloc.buffers(self._sc.stream):
                    r = cam.create_request()
                    r.add_buffer(self._sc.stream, buf)
                    reqs.append(r)
            self._requests = reqs
            # Drain any stale completed requests before starting the newly acquired sensor.
            self.cm.get_ready_requests()
            cam.start()
            self._started = True
            if self._ae is not None:
                try:
                    self._ae.apply_initial()
                except Exception:
                    self._ae.close()
                    self._ae = None
            for r in self._requests:
                cam.queue_request(r)
        except Exception:
            self._close_camera()
            raise

    def _close_camera(self):
        if self._ae is not None:
            try:
                self._ae.close()
            except Exception:
                pass
            self._ae = None

        if self._v4l2 is not None:
            try:
                self._v4l2.release()
            except Exception:
                pass
            self._v4l2 = None

        if self._cam is not None:
            try:
                if self._started:
                    self._cam.stop()
            except Exception:
                pass
            self._started = False
            if self.cm is not None:
                try:
                    self.cm.get_ready_requests()
                except Exception:
                    pass
            self._requests = []
            self._alloc = None
            self._sc = None
            self._raw_sc = None
            try:
                self._cam.release()
            except Exception:
                pass
            self._cam = None

    def _read_libcamera_frame(self, cam_info, high_quality=False, target_size=(960, 720)):
        ready = self.cm.get_ready_requests()
        if not ready:
            return None
        frame = None
        latest_stats = None
        for req in ready:
            if req.status == self.libcamera.Request.Status.Complete:
                if self._raw_sc is not None and self._raw_sc.stream in req.buffers:
                    buf = req.buffers[self._raw_sc.stream]
                    plane = buf.planes[0]
                    w = self._raw_sc.size.width
                    h = self._raw_sc.size.height
                    stride = self._raw_sc.stride
                    fmt = str(self._raw_sc.pixel_format)
                    if "CSI2P" in fmt.upper():
                        with mmap.mmap(plane.fd, plane.offset + plane.length, mmap.MAP_SHARED, mmap.PROT_READ) as mm:
                            frame, latest_stats = debayer_quad_csi2p(
                                mm,
                                w,
                                h,
                                stride,
                                rot=cam_info.rotation,
                                offset=plane.offset,
                                target_size=target_size,
                                high_quality=high_quality,
                                tone_lut=self._tone_lut,
                                return_stats=True,
                                cv2_mod=self.cv2,
                                np_mod=self.np,
                            )
                elif self._sc is not None and self._sc.stream in req.buffers:
                    buf = req.buffers[self._sc.stream]
                    plane = buf.planes[0]
                    w = self._sc.size.width
                    h = self._sc.size.height
                    stride = self._sc.stride
                    fmt = str(self._sc.pixel_format)
                    with mmap.mmap(plane.fd, plane.offset + plane.length, mmap.MAP_SHARED, mmap.PROT_READ) as mm:
                        raw = mm[plane.offset:plane.offset + plane.length]
                    frame = convert_frame(
                        raw,
                        w,
                        h,
                        stride,
                        fmt,
                        rot=cam_info.rotation,
                        cv2_mod=self.cv2,
                        np_mod=self.np,
                    )
            self._requeue(req)
        if latest_stats is not None and self._ae is not None:
            try:
                self._ae.update(*latest_stats)
            except Exception:
                pass
        return frame

    def _run_loop(self):
        try:
            self._open_camera(self.active_camera)
        except Exception as exc:
            if self.on_error:
                self.on_error(str(exc))
            return

        try:
            while not self._stop_event.is_set():
                # 1. Pending camera switch?
                switch_to = None
                with self._lock:
                    if self._want_switch is not None:
                        switch_to = self._want_switch
                        self._want_switch = None
                if switch_to is not None and switch_to != self.active_index:
                    self._close_camera()
                    self.active_index = switch_to
                    try:
                        self._open_camera(self.active_camera)
                        if self.on_camera_changed:
                            self.on_camera_changed()
                    except Exception as exc:
                        if self.on_error:
                            self.on_error("Switch failed: %s" % exc)
                        break

                # 2. Pending full-resolution still capture?
                still_out = None
                with self._lock:
                    if self._still_request is not None:
                        still_out = self._still_request
                        self._still_request = None
                if still_out is not None:
                    self._perform_still_capture(still_out)

                info = self.active_camera
                if info is None:
                    time.sleep(0.05)
                    continue

                # 3. Capture next live frame.
                frame = None
                if info.backend == "v4l2":
                    if self._v4l2 is not None:
                        ok, f = self._v4l2.read()
                        if ok and f is not None:
                            frame = self.np.ascontiguousarray(f)
                        else:
                            time.sleep(0.02)
                else:
                    frame = self._read_libcamera_frame(info)
                    if frame is None:
                        time.sleep(0.008)

                if frame is not None:
                    with self._lock:
                        self._latest_bgr = frame
                        self._latest_seq += 1
                    self._push_video_frame(frame)
                    if self.on_frame:
                        self.on_frame()
        finally:
            self.stop_video()
            self._close_camera()

    def _perform_still_capture(self, dst_path):
        info = self.active_camera
        try:
            if info.backend == "libcamera" and self._raw_sc is not None:
                captured = None
                deadline = time.monotonic() + 4.0
                while time.monotonic() < deadline and not self._stop_event.is_set():
                    captured = self._read_libcamera_frame(info, high_quality=True, target_size=None)
                    if captured is not None:
                        break
                    time.sleep(0.01)
                if captured is None:
                    raise RuntimeError("still capture timed out")
                os.makedirs(os.path.dirname(dst_path), exist_ok=True)
                if not self.cv2.imwrite(dst_path, captured, [self.cv2.IMWRITE_JPEG_QUALITY, 95]):
                    raise RuntimeError("failed to write %s" % dst_path)
                self._still_result = (dst_path, None)
            elif info.backend == "libcamera":
                self._close_camera()
                self._open_camera(info, role_name="still", target_sizes=PREFERRED_STILL_SIZES)
                captured = None
                deadline = time.monotonic() + 5.0
                warmup = 0
                while time.monotonic() < deadline and not self._stop_event.is_set():
                    f = self._read_libcamera_frame(info)
                    if f is not None:
                        captured = f
                        warmup += 1
                        if warmup >= 6:
                            break
                    else:
                        time.sleep(0.01)
                self._close_camera()
                self._open_camera(info, role_name="viewfinder", target_sizes=[DEFAULT_VIEWFINDER_SIZE])
                if captured is None:
                    raise RuntimeError("still capture timed out")
                os.makedirs(os.path.dirname(dst_path), exist_ok=True)
                ok = self.cv2.imwrite(dst_path, captured, [self.cv2.IMWRITE_JPEG_QUALITY, 95])
                if not ok:
                    raise RuntimeError("failed to write %s" % dst_path)
                self._still_result = (dst_path, None)
            else:
                frame, _ = self.latest_frame()
                if frame is None:
                    raise RuntimeError("no frame yet")
                os.makedirs(os.path.dirname(dst_path), exist_ok=True)
                ok = self.cv2.imwrite(dst_path, frame, [self.cv2.IMWRITE_JPEG_QUALITY, 95])
                if not ok:
                    raise RuntimeError("failed to write %s" % dst_path)
                self._still_result = (dst_path, None)
        except Exception as exc:
            self._still_result = (None, str(exc))
            # Recover viewfinder if still capture interrupted it.
            if self._cam is None and self._v4l2 is None and info is not None:
                try:
                    self._open_camera(info, role_name="viewfinder", target_sizes=[DEFAULT_VIEWFINDER_SIZE])
                except Exception:
                    pass
        finally:
            self._still_done.set()

    def capture_photo(self, high_res=False, dst_path=None):
        """Save a JPEG photo into ~/Pictures/Camera (or dst_path) and return its path."""
        if dst_path is None:
            os.makedirs(PICTURE_DIR, exist_ok=True)
            stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
            dst_path = os.path.join(PICTURE_DIR, "IMG_%s.jpg" % stamp)
            suffix = 1
            while os.path.exists(dst_path):
                dst_path = os.path.join(PICTURE_DIR, "IMG_%s_%d.jpg" % (stamp, suffix))
                suffix += 1

        if not high_res:
            frame, _ = self.latest_frame()
            if frame is None:
                raise RuntimeError("camera is still warming up")
            os.makedirs(os.path.dirname(dst_path), exist_ok=True)
            if not self.cv2.imwrite(dst_path, frame, [self.cv2.IMWRITE_JPEG_QUALITY, 95]):
                raise RuntimeError("failed to save %s" % dst_path)
            return dst_path

        self._still_done.clear()
        self._still_result = (None, None)
        with self._lock:
            self._still_request = dst_path
        if not self._still_done.wait(timeout=12.0):
            raise RuntimeError("high-res capture timed out")
        saved, err = self._still_result
        if err:
            raise RuntimeError(err)
        return saved

    def start_video(self, dst_path=None):
        """Start recording H.264 MP4 from upright viewfinder frames via ffmpeg."""
        if shutil.which("ffmpeg") is None:
            raise RuntimeError("ffmpeg is not installed")
        frame, _ = self.latest_frame()
        if frame is None:
            raise RuntimeError("camera is still warming up")
        even = ensure_even_frame(frame)
        h, w = even.shape[:2]

        if dst_path is None:
            os.makedirs(VIDEO_DIR, exist_ok=True)
            stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
            dst_path = os.path.join(VIDEO_DIR, "VID_%s.mp4" % stamp)
            suffix = 1
            while os.path.exists(dst_path):
                dst_path = os.path.join(VIDEO_DIR, "VID_%s_%d.mp4" % (stamp, suffix))
                suffix += 1
        else:
            os.makedirs(os.path.dirname(dst_path) or ".", exist_ok=True)

        cmd = [
            "ffmpeg",
            "-y",
            "-loglevel",
            "error",
            "-f",
            "rawvideo",
            "-pix_fmt",
            "bgr24",
            "-s",
            "%dx%d" % (w, h),
            "-r",
            "20",
            "-i",
            "-",
            "-c:v",
            "libx264",
            "-preset",
            "ultrafast",
            "-tune",
            "zerolatency",
            "-pix_fmt",
            "yuv420p",
            "-movflags",
            "+faststart",
            dst_path,
        ]
        proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
        q = queue.Queue(maxsize=6)

        def writer():
            try:
                while True:
                    item = q.get()
                    if item is None:
                        break
                    if proc.stdin is not None:
                        proc.stdin.write(item)
            except Exception:
                pass
            finally:
                try:
                    if proc.stdin is not None:
                        proc.stdin.close()
                except Exception:
                    pass

        wt = threading.Thread(target=writer, name="chandra-cam-rec", daemon=True)
        with self._rec_lock:
            self._rec_proc = proc
            self._rec_queue = q
            self._rec_thread = wt
            self._rec_path = dst_path
            self._rec_start_mono = time.monotonic()
            self._rec_frames = 0
            self._rec_size = (w, h)
        wt.start()
        self._push_video_frame(frame)
        return dst_path

    def _push_video_frame(self, frame):
        with self._rec_lock:
            q = self._rec_queue
            proc = self._rec_proc
            target_size = self._rec_size
            if q is None or proc is None or proc.poll() is not None:
                return
        even = ensure_even_frame(frame)
        h, w = even.shape[:2]
        if target_size and (w, h) != target_size:
            even = self.cv2.resize(even, target_size)
        raw = even.tobytes()
        try:
            q.put_nowait(raw)
            with self._rec_lock:
                self._rec_frames += 1
        except queue.Full:
            # Drop oldest queued frame so live preview remains responsive.
            try:
                q.get_nowait()
            except queue.Empty:
                pass
            try:
                q.put_nowait(raw)
                with self._rec_lock:
                    self._rec_frames += 1
            except queue.Full:
                pass

    def stop_video(self):
        """Stop video recording and finalize the MP4 container cleanly."""
        with self._rec_lock:
            proc = self._rec_proc
            q = self._rec_queue
            wt = self._rec_thread
            path = self._rec_path
            frames = self._rec_frames
            self._rec_proc = None
            self._rec_queue = None
            self._rec_thread = None
            self._rec_path = None
            self._rec_frames = 0
            self._rec_size = None

        if proc is None:
            return None, 0
        if q is not None:
            try:
                while not q.empty():
                    try:
                        q.get_nowait()
                    except queue.Empty:
                        break
                q.put_nowait(None)
            except Exception:
                pass
        if wt is not None:
            wt.join(timeout=5.0)
        rc = proc.wait(timeout=10.0)
        if rc != 0 and proc.stderr is not None:
            err = proc.stderr.read().decode("utf-8", "replace").strip()
            if err and self.on_error:
                self.on_error("Video encode error: " + err)
        return path, frames


def list_gallery_photos():
    """Return newest-first list of saved photos in ~/Pictures/Camera."""
    if not os.path.isdir(PICTURE_DIR):
        return []
    files = []
    for name in os.listdir(PICTURE_DIR):
        if name.lower().endswith(IMAGE_EXTS):
            p = os.path.join(PICTURE_DIR, name)
            if os.path.isfile(p):
                files.append(p)
    files.sort(key=lambda p: (os.path.getmtime(p), p), reverse=True)
    return files


def run_worker(cameras, initial_index):
    """Stream Cairo BGRA viewfinder frames to stdout and handle UI commands on stdin."""
    import cv2

    write_lock = threading.Lock()
    has_flash = 1 if os.path.exists(FLASH_LED_PATH) else 0
    stop_flag = threading.Event()
    last_sent = [0.0]

    def emit(line):
        data = (line + "\n").encode("utf-8", "replace")
        with write_lock:
            try:
                sys.stdout.buffer.write(data)
                sys.stdout.buffer.flush()
            except (BrokenPipeError, OSError):
                stop_flag.set()

    def emit_active(info, idx):
        if info is None:
            emit("active -1 0 0 No camera")
        else:
            emit("active %d %d %d %s" % (
                idx,
                1 if info.is_front else 0,
                1 if info.is_back else 0,
                info.label,
            ))

    engine_holder = [None]

    def on_frame():
        if stop_flag.is_set():
            return
        now = time.monotonic()
        if now - last_sent[0] < 0.045:
            return
        eng = engine_holder[0]
        if eng is None:
            return
        frame, _ = eng.latest_frame()
        if frame is None:
            return
        last_sent[0] = now
        h, w = frame.shape[:2]
        max_dim = max(w, h)
        if max_dim > 640:
            scale = 640.0 / float(max_dim)
            pw = max(2, int(round(w * scale)))
            ph = max(2, int(round(h * scale)))
            preview = cv2.resize(frame, (pw, ph), interpolation=cv2.INTER_AREA)
        else:
            pw, ph = w, h
            preview = frame
        raw = bgr_to_cairo_argb32(preview, np_mod=eng.np).tobytes()
        hdr = ("frame %d %d %d\n" % (pw, ph, len(raw))).encode("ascii")
        with write_lock:
            try:
                sys.stdout.buffer.write(hdr)
                sys.stdout.buffer.write(raw)
                sys.stdout.buffer.flush()
            except (BrokenPipeError, OSError):
                stop_flag.set()

    def on_camera_changed():
        eng = engine_holder[0]
        if eng is not None:
            emit_active(eng.active_camera, eng.active_index)
            emit("flash 0")

    engine = CameraEngine(
        cameras,
        initial_index=initial_index,
        on_frame=on_frame,
        on_error=lambda msg: emit("toast " + str(msg).replace("\n", " ")),
        on_camera_changed=on_camera_changed,
    )
    engine_holder[0] = engine

    def _sig_stop(*_):
        stop_flag.set()

    signal.signal(signal.SIGINT, _sig_stop)
    signal.signal(signal.SIGTERM, _sig_stop)

    emit("info %d %d" % (len(cameras), has_flash))
    emit_active(engine.active_camera, engine.active_index)
    if cameras:
        engine.start()
    else:
        emit("toast No camera connected")

    try:
        while not stop_flag.is_set():
            line = sys.stdin.readline()
            if not line:
                break
            cmd = line.strip()
            if not cmd:
                continue
            if cmd == "quit":
                break
            if cmd == "switch":
                set_flash_led(False)
                engine.cycle_camera()
            elif cmd in ("snap", "snap_full"):
                high_res = cmd == "snap_full"

                def snap_job(hr=high_res):
                    try:
                        p = engine.capture_photo(high_res=hr)
                        emit("saved_photo " + p)
                    except Exception as exc:
                        emit("toast " + str(exc).replace("\n", " "))

                threading.Thread(target=snap_job, daemon=True).start()
            elif cmd == "rec_start":
                try:
                    engine.start_video()
                    emit("rec_state 1")
                except Exception as exc:
                    emit("toast " + str(exc).replace("\n", " "))
            elif cmd == "rec_stop":
                try:
                    p, frames = engine.stop_video()
                    emit("rec_state 0")
                    if p:
                        emit("saved_video %d %s" % (frames, p))
                except Exception as exc:
                    emit("rec_state 0")
                    emit("toast " + str(exc).replace("\n", " "))
            elif cmd.startswith("flash "):
                want_on = cmd.split(None, 1)[1].strip() in ("1", "on", "true")
                if want_on:
                    if set_flash_led(True):
                        emit("flash 1")
                    else:
                        emit("flash 0")
                        emit("toast Flash control unavailable")
                else:
                    set_flash_led(False)
                    emit("flash 0")
    finally:
        engine.stop()
        set_flash_led(False)
    return 0


def launch_ui(args):
    """Execute the native GTK3 + Cairo UI binary pointing back to this worker."""
    repo_ui = os.path.join(
        os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
        "build",
        "chandra-camera-ui",
    )
    candidates = [
        os.environ.get("CHANDRA_CAMERA_UI", ""),
        repo_ui,
        "/usr/local/lib/chandra/chandra-camera-ui",
    ]
    ui_bin = next((p for p in candidates if p and os.access(p, os.X_OK)), "")
    if not ui_bin:
        print(
            "chandra-camera: UI binary not found (checked CHANDRA_CAMERA_UI, %s, /usr/local/lib/chandra/chandra-camera-ui)"
            % repo_ui,
            file=sys.stderr,
        )
        return 1

    cmd = [ui_bin, "--worker-exe", os.path.abspath(__file__)]
    if args.camera:
        cmd += ["--camera", args.camera]
    if args.open_gallery:
        cmd.append("--open-gallery")
    os.execv(ui_bin, cmd)


def run_self_test(cameras):
    """Verify multi-camera discovery, switching, JPEG capture, MP4 recording, and clean release."""
    if not cameras:
        print("FAIL: no cameras discovered", file=sys.stderr)
        return 1
    print("Discovered %d camera(s):" % len(cameras))
    for i, c in enumerate(cameras):
        print("  [%d] %s (%s, cid=%s, rot=%d, max_px=%d)" % (i, c.label, c.backend, c.cid, c.rotation, c.max_pixels))

    front_idx = select_initial_camera(cameras, "front")
    engine = CameraEngine(cameras, initial_index=0)
    engine.start()
    try:
        # 1. Wait for first camera frames.
        t0 = time.monotonic()
        while time.monotonic() - t0 < 5.0:
            f, seq = engine.latest_frame()
            if f is not None and seq >= 3:
                break
            time.sleep(0.05)
        f0, seq0 = engine.latest_frame()
        if f0 is None:
            raise RuntimeError("no frames from initial camera %s" % cameras[0].label)
        print("Initial camera %s frame: shape=%s seq=%d" % (cameras[0].label, f0.shape, seq0))

        # 2. Switch to front camera if different and capture JPEG photo + 2s H.264 video.
        if front_idx != engine.active_index:
            engine.switch_camera(front_idx)
            t0 = time.monotonic()
            while time.monotonic() - t0 < 5.0:
                if engine.active_index == front_idx:
                    f, seq = engine.latest_frame()
                    if f is not None and seq > seq0 + 3:
                        break
                time.sleep(0.05)

        f1, _ = engine.latest_frame()
        if f1 is None or int(f1.max()) == 0:
            raise RuntimeError("active camera %s produced empty/black frame" % engine.active_camera.label)
        print("Active photo camera %s frame: shape=%s mean=%.1f max=%d" % (
            engine.active_camera.label, f1.shape, float(f1.mean()), int(f1.max())
        ))

        photo_path = engine.capture_photo(high_res=False)
        import cv2
        saved_img = cv2.imread(photo_path)
        if saved_img is None or os.path.getsize(photo_path) <= 0:
            raise RuntimeError("invalid captured photo at %s" % photo_path)
        print("Saved JPEG: %s (%d bytes, shape=%s)" % (photo_path, os.path.getsize(photo_path), saved_img.shape))

        video_path = engine.start_video()
        time.sleep(2.0)
        final_video, nframes = engine.stop_video()
        if not final_video or not os.path.exists(final_video) or os.path.getsize(final_video) <= 0 or nframes < 5:
            raise RuntimeError("invalid captured video at %s (frames=%d)" % (final_video, nframes))
        print("Saved MP4: %s (%d bytes, frames=%d)" % (final_video, os.path.getsize(final_video), nframes))

        # 3. Switch back to camera 0 to prove bidirectional switch cleanly releases qcom-camss.
        if len(cameras) > 1:
            back_target = 0 if engine.active_index != 0 else 1
            _, seq_before_back = engine.latest_frame()
            engine.switch_camera(back_target)
            t0 = time.monotonic()
            ok_back = False
            while time.monotonic() - t0 < 5.0:
                if engine.active_index == back_target:
                    fb, seqb = engine.latest_frame()
                    if fb is not None and seqb > seq_before_back + 1:
                        ok_back = True
                        print("Switched back to %s: shape=%s seq=%d" % (cameras[back_target].label, fb.shape, seqb))
                        break
                time.sleep(0.05)
            if not ok_back:
                raise RuntimeError("timed out switching back to camera %s" % cameras[back_target].label)
    finally:
        engine.stop()

    print("SELF_TEST_OK photo=%s video=%s" % (photo_path, final_video))
    return 0


def parse_args(argv):
    p = argparse.ArgumentParser(prog=APP_ID, description="Chandra Wayland Camera App")
    p.add_argument("--camera", default="", help="Initial camera ('back', 'front', index, or model/id)")
    p.add_argument("--open-gallery", action="store_true", help="Open directly in the in-app gallery")
    p.add_argument("--worker", action="store_true", help="Run stdio frame/control worker for native UI")
    p.add_argument("--self-test", action="store_true", help="Run non-interactive capture & switch self-test")
    p.add_argument("--list-cameras", action="store_true", help="List detected cameras and exit")
    return p.parse_args(argv)


def main(argv=None):
    args = parse_args(sys.argv[1:] if argv is None else argv)
    if args.list_cameras or args.self_test or args.worker:
        cameras = discover_cameras()
        if args.list_cameras:
            for i, c in enumerate(cameras):
                print("%d\t%s\t%s\t%s\trot=%d" % (i, c.label, c.backend, c.cid, c.rotation))
            return 0
        if args.self_test:
            return run_self_test(cameras)
        initial = select_initial_camera(cameras, args.camera)
        return run_worker(cameras, initial_index=initial)
    return launch_ui(args)


if __name__ == "__main__":
    sys.exit(main())
