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

import argparse
from dataclasses import dataclass
import datetime
import mmap
import os
import queue
import shutil
import signal
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))


def debayer_quad_csi2p(
    raw_buf,
    width,
    height,
    stride,
    rot=0,
    offset=0,
    target_size=(960, 720),
    high_quality=False,
    gamma_lut=None,
    cv2_mod=None,
    np_mod=None,
):
    """Debayer 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB 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))
    row_bytes = (width // 4) * 5
    even_h = (height // 2) * 2
    even_w = (width // 4) * 4
    if high_quality:
        p8 = arr[:even_h, :row_bytes].reshape((even_h, even_w // 4, 5))[:, :, :4].reshape((even_h, even_w))
        bayer = (
            (
                p8[0::2, 0::2].astype(np_mod.uint16)
                + p8[0::2, 1::2]
                + p8[1::2, 0::2]
                + p8[1::2, 1::2]
            )
            >> 2
        ).astype(np_mod.uint8)
    else:
        b5 = arr[:even_h:2, :row_bytes].reshape((even_h // 2, even_w // 4, 5))
        bayer = np_mod.ascontiguousarray(b5[:, :, [0, 2]].reshape((even_h // 2, even_w // 2)))

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

    f = np_mod.maximum(bgr.astype(np_mod.float32) - 16.0, 0.0)
    means = f.mean(axis=(0, 1))
    avg = float(means.mean())
    if avg > 1.0:
        gains = np_mod.clip(avg / np_mod.maximum(means, 1.0), 0.65, 2.2)
        boost = float(np_mod.clip(75.0 / avg, 1.0, 3.8))
        u8 = np_mod.clip(f * (gains * boost), 0, 255).astype(np_mod.uint8)
    else:
        u8 = np_mod.clip(f, 0, 255).astype(np_mod.uint8)
    if gamma_lut is None:
        gamma_lut = np_mod.clip((np_mod.linspace(0.0, 1.0, 256) ** (1.0 / 2.2)) * 255.0, 0, 255).astype(np_mod.uint8)
    out = cv2_mod.LUT(u8, gamma_lut)
    return np_mod.ascontiguousarray(rotate_bgr(out, rot, cv2_mod))


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._started = False
        self._reuse_arg = None
        self._gamma_lut = np.clip((np.linspace(0.0, 1.0, 256) ** (1.0 / 2.2)) * 255.0, 0, 255).astype(np.uint8)

        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._raw_sc = None
            configured = False
            if role_name == "viewfinder" and info.model.lower() in QUAD_BAYER_MODELS:
                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)
            if alloc.allocate(self._sc.stream) <= 0:
                raise RuntimeError("failed to allocate camera buffers for %s" % info.label)
            self._alloc = alloc
            reqs = []
            if 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 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)
            else:
                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
            for r in self._requests:
                cam.queue_request(r)
        except Exception:
            self._close_camera()
            raise

    def _close_camera(self):
        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
        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 = debayer_quad_csi2p(
                                mm,
                                w,
                                h,
                                stride,
                                rot=cam_info.rotation,
                                offset=plane.offset,
                                target_size=target_size,
                                high_quality=high_quality,
                                gamma_lut=self._gamma_lut,
                                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)
        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())
