#!/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")

# 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 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)

    rot_i = int(rot) % 360
    if rot_i == 90:
        return np_mod.ascontiguousarray(cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_CLOCKWISE))
    if rot_i == 180:
        return np_mod.ascontiguousarray(cv2_mod.rotate(bgr, cv2_mod.ROTATE_180))
    if rot_i == 270:
        return np_mod.ascontiguousarray(cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_COUNTERCLOCKWISE))
    return bgr


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._alloc = None
        self._requests = []
        self._v4l2 = None
        self._started = False
        self._reuse_arg = None

        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:
            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
            configured = False
            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 = []
            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
            try:
                self._cam.release()
            except Exception:
                pass
            self._cam = None

    def _read_libcamera_frame(self, cam_info):
        ready = self.cm.get_ready_requests()
        if not ready:
            return None
        frame = None
        for req in ready:
            if self._sc is not None and self._sc.stream in req.buffers:
                if req.status == self.libcamera.Request.Status.Complete:
                    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":
                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_gui(cameras, initial_index, open_gallery=False):
    """Launch the GTK3 + Cairo mobile camera interface on Wayland."""
    os.environ.setdefault("GDK_BACKEND", "wayland")
    import cairo
    import cv2
    import gi
    gi.require_version("Gtk", "3.0")
    from gi.repository import Gdk, GLib, Gtk

    GLib.set_prgname(APP_ID)
    GLib.set_application_name(APP_TITLE)

    css = b"""
    window, .cam-root {
        background-color: #0b0d14;
        color: #f4f6fc;
    }
    .cam-pill {
        background-color: rgba(14, 18, 30, 0.74);
        color: #f4f6fc;
        border: 1px solid rgba(255, 255, 255, 0.16);
        border-radius: 18px;
        padding: 5px 12px;
        font-size: 13px;
        font-weight: 600;
        min-height: 24px;
    }
    .cam-pill:hover {
        background-color: rgba(30, 38, 60, 0.88);
    }
    .cam-pill-active {
        background-color: rgba(110, 140, 255, 0.88);
        color: #090d16;
        border-color: rgba(180, 200, 255, 0.9);
    }
    .cam-pill-danger {
        background-color: rgba(239, 68, 68, 0.88);
        color: #ffffff;
        border-color: rgba(255, 180, 180, 0.8);
    }
    .cam-dock {
        background-color: rgba(10, 12, 20, 0.86);
        border-top: 1px solid rgba(255, 255, 255, 0.10);
        padding: 10px 16px 14px 16px;
    }
    .cam-mode-bar {
        background-color: rgba(255, 255, 255, 0.08);
        border-radius: 18px;
        padding: 3px;
    }
    .cam-mode-btn {
        background-color: transparent;
        color: #c2cadc;
        border: none;
        border-radius: 15px;
        padding: 4px 18px;
        font-size: 13px;
        font-weight: 600;
        min-height: 22px;
    }
    .cam-mode-selected {
        background-color: #6e8cff;
        color: #0b0d14;
    }
    .cam-mode-selected-video {
        background-color: #ef4444;
        color: #ffffff;
    }
    .cam-rec-badge {
        background-color: rgba(239, 68, 68, 0.90);
        color: #ffffff;
        border-radius: 12px;
        padding: 2px 10px;
        font-size: 12px;
        font-weight: 700;
    }
    .cam-icon-btn {
        background-color: transparent;
        border: none;
        padding: 0;
        box-shadow: none;
    }
    .cam-gallery-bar {
        background-color: #111523;
        border-bottom: 1px solid rgba(255, 255, 255, 0.10);
        padding: 8px 12px;
    }
    .cam-gallery-foot {
        background-color: #111523;
        border-top: 1px solid rgba(255, 255, 255, 0.10);
        padding: 8px 14px;
    }
    .cam-title {
        font-size: 14px;
        font-weight: 700;
        color: #f4f6fc;
    }
    .cam-sub {
        font-size: 12px;
        color: #9ba6c2;
    }
    """
    provider = Gtk.CssProvider()
    provider.load_from_data(css)
    Gtk.StyleContext.add_provider_for_screen(
        Gdk.Screen.get_default(), provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
    )

    class CameraWindow(Gtk.Window):
        def __init__(self):
            super().__init__(title=APP_TITLE)
            self.set_wmclass(APP_ID, APP_TITLE)
            self.set_default_size(520, 960)
            self.set_size_request(340, 480)
            self.get_style_context().add_class("cam-root")

            self.mode = "photo"  # "photo" | "video"
            self.high_res = False
            self.show_grid = False
            self.torch_on = False
            self.timer_sec = 0  # 0, 3, 10
            self.countdown_left = 0
            self._countdown_src = None
            self._flash_alpha = 0.0
            self._toast_text = ""
            self._toast_until = 0.0
            self._draw_pending = False
            self._thumb_bgr = None
            self._gallery_files = []
            self._gallery_idx = 0
            self._gallery_bgr = None
            self._has_flash_led = os.path.exists(FLASH_LED_PATH)

            self.engine = CameraEngine(
                cameras,
                initial_index=initial_index,
                on_frame=self._on_worker_frame,
                on_error=self._on_worker_error,
                on_camera_changed=lambda: GLib.idle_add(lambda: (self._sync_ui_labels(), False)[1]),
            )

            self.stack = Gtk.Stack()
            self.stack.set_transition_type(Gtk.StackTransitionType.SLIDE_LEFT_RIGHT)
            self.stack.set_transition_duration(180)
            self.add(self.stack)

            self._build_viewfinder_page()
            self._build_gallery_page()

            self.connect("delete-event", self._on_close)
            self.connect("key-press-event", self._on_key_press)

            self._refresh_thumbnail()
            self._sync_ui_labels()

            if open_gallery:
                self._open_gallery()
            else:
                self.stack.set_visible_child_name("viewfinder")

            if cameras:
                self.engine.start()
            else:
                self._show_toast("No camera found", 6.0)

            GLib.timeout_add(250, self._tick_ui)

        def _build_viewfinder_page(self):
            overlay = Gtk.Overlay()

            self.view_area = Gtk.DrawingArea()
            self.view_area.set_hexpand(True)
            self.view_area.set_vexpand(True)
            self.view_area.connect("draw", self._draw_viewfinder)
            overlay.add(self.view_area)

            # Top overlay controls.
            top_bar = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
            top_bar.set_halign(Gtk.Align.FILL)
            top_bar.set_valign(Gtk.Align.START)
            top_bar.set_margin_top(12)
            top_bar.set_margin_start(12)
            top_bar.set_margin_end(12)

            self.cam_badge_btn = Gtk.Button(label="Camera")
            self.cam_badge_btn.get_style_context().add_class("cam-pill")
            self.cam_badge_btn.set_can_focus(False)
            self.cam_badge_btn.connect("clicked", lambda *_: self._switch_camera())
            top_bar.pack_start(self.cam_badge_btn, False, False, 0)

            spacer = Gtk.Box()
            top_bar.pack_start(spacer, True, True, 0)

            self.flash_btn = Gtk.Button(label="Flash")
            self.flash_btn.get_style_context().add_class("cam-pill")
            self.flash_btn.set_can_focus(False)
            self.flash_btn.connect("clicked", lambda *_: self._toggle_flash())
            top_bar.pack_start(self.flash_btn, False, False, 0)

            self.grid_btn = Gtk.Button(label="Grid")
            self.grid_btn.get_style_context().add_class("cam-pill")
            self.grid_btn.set_can_focus(False)
            self.grid_btn.connect("clicked", lambda *_: self._toggle_grid())
            top_bar.pack_start(self.grid_btn, False, False, 0)

            self.timer_btn = Gtk.Button(label="Timer")
            self.timer_btn.get_style_context().add_class("cam-pill")
            self.timer_btn.set_can_focus(False)
            self.timer_btn.connect("clicked", lambda *_: self._cycle_timer())
            top_bar.pack_start(self.timer_btn, False, False, 0)

            self.res_btn = Gtk.Button(label="HD")
            self.res_btn.get_style_context().add_class("cam-pill")
            self.res_btn.set_can_focus(False)
            self.res_btn.connect("clicked", lambda *_: self._toggle_res())
            top_bar.pack_start(self.res_btn, False, False, 0)

            overlay.add_overlay(top_bar)

            # Bottom dock (mode switcher + gallery/shutter/flip row).
            dock = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
            dock.get_style_context().add_class("cam-dock")
            dock.set_halign(Gtk.Align.FILL)
            dock.set_valign(Gtk.Align.END)

            mode_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
            mode_row.set_halign(Gtk.Align.CENTER)

            mode_pill = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=2)
            mode_pill.get_style_context().add_class("cam-mode-bar")
            self.photo_mode_btn = Gtk.Button(label="Photo")
            self.photo_mode_btn.get_style_context().add_class("cam-mode-btn")
            self.photo_mode_btn.set_can_focus(False)
            self.photo_mode_btn.connect("clicked", lambda *_: self._set_mode("photo"))
            self.video_mode_btn = Gtk.Button(label="Video")
            self.video_mode_btn.get_style_context().add_class("cam-mode-btn")
            self.video_mode_btn.set_can_focus(False)
            self.video_mode_btn.connect("clicked", lambda *_: self._set_mode("video"))
            mode_pill.pack_start(self.photo_mode_btn, False, False, 0)
            mode_pill.pack_start(self.video_mode_btn, False, False, 0)
            mode_row.pack_start(mode_pill, False, False, 0)

            self.rec_label = Gtk.Label(label="● 00:00")
            self.rec_label.get_style_context().add_class("cam-rec-badge")
            self.rec_label.set_no_show_all(True)
            self.rec_label.hide()
            mode_row.pack_start(self.rec_label, False, False, 0)
            dock.pack_start(mode_row, False, False, 0)

            action_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
            action_row.set_homogeneous(True)

            # Gallery button (left)
            self.gallery_btn = Gtk.Button()
            self.gallery_btn.get_style_context().add_class("cam-icon-btn")
            self.gallery_btn.set_halign(Gtk.Align.CENTER)
            self.gallery_btn.set_valign(Gtk.Align.CENTER)
            self.gallery_btn.set_size_request(56, 56)
            self.gallery_btn.set_can_focus(False)
            self.gallery_btn.set_tooltip_text("Open Camera Gallery")
            self.thumb_area = Gtk.DrawingArea()
            self.thumb_area.set_size_request(52, 52)
            self.thumb_area.connect("draw", self._draw_thumb_button)
            self.gallery_btn.add(self.thumb_area)
            self.gallery_btn.connect("clicked", lambda *_: self._open_gallery())
            action_row.pack_start(self.gallery_btn, True, True, 0)

            # Shutter button (center)
            self.shutter_btn = Gtk.Button()
            self.shutter_btn.get_style_context().add_class("cam-icon-btn")
            self.shutter_btn.set_halign(Gtk.Align.CENTER)
            self.shutter_btn.set_valign(Gtk.Align.CENTER)
            self.shutter_btn.set_size_request(76, 76)
            self.shutter_btn.set_can_focus(False)
            self.shutter_btn.set_tooltip_text("Take Photo / Record Video (Space)")
            self.shutter_area = Gtk.DrawingArea()
            self.shutter_area.set_size_request(76, 76)
            self.shutter_area.connect("draw", self._draw_shutter_button)
            self.shutter_btn.add(self.shutter_area)
            self.shutter_btn.connect("clicked", lambda *_: self._on_shutter())
            action_row.pack_start(self.shutter_btn, True, True, 0)

            # Switch camera button (right)
            self.switch_btn = Gtk.Button()
            self.switch_btn.get_style_context().add_class("cam-icon-btn")
            self.switch_btn.set_halign(Gtk.Align.CENTER)
            self.switch_btn.set_valign(Gtk.Align.CENTER)
            self.switch_btn.set_size_request(56, 56)
            self.switch_btn.set_can_focus(False)
            self.switch_btn.set_tooltip_text("Switch Camera (S)")
            self.switch_area = Gtk.DrawingArea()
            self.switch_area.set_size_request(52, 52)
            self.switch_area.connect("draw", self._draw_switch_button)
            self.switch_btn.add(self.switch_area)
            self.switch_btn.connect("clicked", lambda *_: self._switch_camera())
            action_row.pack_start(self.switch_btn, True, True, 0)

            dock.pack_start(action_row, False, False, 0)
            overlay.add_overlay(dock)
            self.stack.add_named(overlay, "viewfinder")

        def _build_gallery_page(self):
            box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)

            bar = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
            bar.get_style_context().add_class("cam-gallery-bar")

            back_btn = Gtk.Button(label="← Camera")
            back_btn.get_style_context().add_class("cam-pill")
            back_btn.set_can_focus(False)
            back_btn.connect("clicked", lambda *_: self._close_gallery())
            bar.pack_start(back_btn, False, False, 0)

            self.gallery_title = Gtk.Label(label="Gallery")
            self.gallery_title.get_style_context().add_class("cam-title")
            self.gallery_title.set_ellipsize(3)  # PANGO_ELLIPSIZE_END
            bar.pack_start(self.gallery_title, True, True, 4)

            folder_btn = Gtk.Button(label="Folder")
            folder_btn.get_style_context().add_class("cam-pill")
            folder_btn.set_can_focus(False)
            folder_btn.connect("clicked", lambda *_: self._open_in_thunar())
            bar.pack_start(folder_btn, False, False, 0)

            self.delete_btn = Gtk.Button(label="Delete")
            self.delete_btn.get_style_context().add_class("cam-pill")
            self.delete_btn.get_style_context().add_class("cam-pill-danger")
            self.delete_btn.set_can_focus(False)
            self.delete_btn.connect("clicked", lambda *_: self._delete_current_photo())
            bar.pack_start(self.delete_btn, False, False, 0)
            box.pack_start(bar, False, False, 0)

            self.gallery_area = Gtk.DrawingArea()
            self.gallery_area.set_hexpand(True)
            self.gallery_area.set_vexpand(True)
            self.gallery_area.connect("draw", self._draw_gallery)
            box.pack_start(self.gallery_area, True, True, 0)

            foot = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
            foot.get_style_context().add_class("cam-gallery-foot")

            self.prev_btn = Gtk.Button(label="‹ Prev")
            self.prev_btn.get_style_context().add_class("cam-pill")
            self.prev_btn.set_can_focus(False)
            self.prev_btn.connect("clicked", lambda *_: self._step_gallery(-1))
            foot.pack_start(self.prev_btn, False, False, 0)

            self.gallery_meta = Gtk.Label(label="")
            self.gallery_meta.get_style_context().add_class("cam-sub")
            foot.pack_start(self.gallery_meta, True, True, 4)

            self.next_btn = Gtk.Button(label="Next ›")
            self.next_btn.get_style_context().add_class("cam-pill")
            self.next_btn.set_can_focus(False)
            self.next_btn.connect("clicked", lambda *_: self._step_gallery(1))
            foot.pack_start(self.next_btn, False, False, 0)
            box.pack_start(foot, False, False, 0)

            self.stack.add_named(box, "gallery")

        def _on_worker_frame(self):
            if self._draw_pending:
                return
            self._draw_pending = True
            GLib.idle_add(self._redraw_from_idle)

        def _redraw_from_idle(self):
            self._draw_pending = False
            if self.stack.get_visible_child_name() == "viewfinder":
                self.view_area.queue_draw()
            return False

        def _on_worker_error(self, msg):
            GLib.idle_add(lambda: (self._show_toast(msg, 4.0), False)[1])

        def _show_toast(self, text, duration=2.2):
            self._toast_text = text
            self._toast_until = time.monotonic() + duration
            self.view_area.queue_draw()

        def _tick_ui(self):
            now = time.monotonic()
            dirty = False
            if self._flash_alpha > 0.01:
                self._flash_alpha = max(0.0, self._flash_alpha - 0.18)
                dirty = True
            if self._toast_text and now > self._toast_until:
                self._toast_text = ""
                dirty = True
            if self.engine.is_recording():
                secs = int(self.engine.recording_elapsed())
                self.rec_label.set_text("● %02d:%02d" % (secs // 60, secs % 60))
                self.rec_label.show()
            else:
                if self.rec_label.get_visible():
                    self.rec_label.hide()
                    self.shutter_area.queue_draw()
            if dirty and self.stack.get_visible_child_name() == "viewfinder":
                self.view_area.queue_draw()
            return True

        def _draw_image_contained(self, cr, width, height, bgr, top_pad=0, bottom_pad=0):
            cr.set_source_rgb(0.043, 0.051, 0.078)
            cr.paint()
            if bgr is None:
                return None
            ih, iw = bgr.shape[:2]
            if iw <= 0 or ih <= 0:
                return None
            avail_h = max(60, height - top_pad - bottom_pad)
            scale = min(width / float(iw), avail_h / float(ih))
            dw = max(1, int(round(iw * scale)))
            dh = max(1, int(round(ih * scale)))
            x = (width - dw) / 2.0
            y = top_pad + (avail_h - dh) / 2.0

            argb = bgr_to_cairo_argb32(bgr)
            surf = cairo.ImageSurface.create_for_data(argb, cairo.FORMAT_RGB24, iw, ih, iw * 4)
            cr.save()
            cr.translate(x, y)
            cr.scale(dw / float(iw), dh / float(ih))
            cr.set_source_surface(surf, 0, 0)
            cr.get_source().set_filter(cairo.FILTER_BILINEAR)
            cr.paint()
            cr.restore()
            return (x, y, dw, dh)

        def _draw_viewfinder(self, widget, cr):
            w = widget.get_allocated_width()
            h = widget.get_allocated_height()
            frame, _ = self.engine.latest_frame()
            info = self.engine.active_camera
            if frame is not None:
                disp = cv2.flip(frame, 1) if (info and info.is_front) else frame
                rect = self._draw_image_contained(cr, w, h, disp, top_pad=56, bottom_pad=138)
            else:
                cr.set_source_rgb(0.043, 0.051, 0.078)
                cr.paint()
                rect = (20, 80, max(100, w - 40), max(120, h - 220))
                cr.set_source_rgba(0.75, 0.80, 0.92, 0.75)
                cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
                cr.set_font_size(16)
                msg = "Starting camera..." if info else "No camera connected"
                ext = cr.text_extents(msg)
                cr.move_to((w - ext.width) / 2.0, h / 2.0 - 30)
                cr.show_text(msg)

            if self.show_grid and rect is not None:
                gx, gy, gw, gh = rect
                cr.set_source_rgba(1.0, 1.0, 1.0, 0.28)
                cr.set_line_width(1.0)
                for frac in (1.0 / 3.0, 2.0 / 3.0):
                    cr.move_to(gx + gw * frac, gy)
                    cr.line_to(gx + gw * frac, gy + gh)
                    cr.move_to(gx, gy + gh * frac)
                    cr.line_to(gx + gw, gy + gh * frac)
                cr.stroke()

            if self.countdown_left > 0:
                cr.set_source_rgba(1.0, 1.0, 1.0, 0.92)
                cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
                cr.set_font_size(84)
                txt = str(self.countdown_left)
                ext = cr.text_extents(txt)
                cr.move_to((w - ext.width) / 2.0, (h - 80 + ext.height) / 2.0)
                cr.show_text(txt)

            if self._flash_alpha > 0.01:
                cr.set_source_rgba(1.0, 1.0, 1.0, self._flash_alpha)
                cr.paint()

            if self._toast_text and time.monotonic() <= self._toast_until:
                cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
                cr.set_font_size(13)
                ext = cr.text_extents(self._toast_text)
                pw = ext.width + 28
                ph = 32
                px = (w - pw) / 2.0
                py = max(72.0, h - 186.0)
                r = 16.0
                cr.new_sub_path()
                cr.arc(px + pw - r, py + r, r, -1.5708, 0)
                cr.arc(px + pw - r, py + ph - r, r, 0, 1.5708)
                cr.arc(px + r, py + ph - r, r, 1.5708, 3.1416)
                cr.arc(px + r, py + r, r, 3.1416, 4.7124)
                cr.close_path()
                cr.set_source_rgba(0.06, 0.08, 0.14, 0.85)
                cr.fill_preserve()
                cr.set_source_rgba(1.0, 1.0, 1.0, 0.20)
                cr.set_line_width(1.0)
                cr.stroke()
                cr.set_source_rgb(0.96, 0.97, 1.0)
                cr.move_to((w - ext.width) / 2.0, py + (ph + ext.height) / 2.0 - 1.0)
                cr.show_text(self._toast_text)

        def _draw_thumb_button(self, widget, cr):
            w = widget.get_allocated_width()
            h = widget.get_allocated_height()
            r = 14.0
            cr.new_sub_path()
            cr.arc(w - r, r, r, -1.5708, 0)
            cr.arc(w - r, h - r, r, 0, 1.5708)
            cr.arc(r, h - r, r, 1.5708, 3.1416)
            cr.arc(r, r, r, 3.1416, 4.7124)
            cr.close_path()
            cr.clip_preserve()

            if self._thumb_bgr is not None:
                th, tw = self._thumb_bgr.shape[:2]
                argb = bgr_to_cairo_argb32(self._thumb_bgr)
                surf = cairo.ImageSurface.create_for_data(argb, cairo.FORMAT_RGB24, tw, th, tw * 4)
                cr.save()
                cr.scale(w / float(tw), h / float(th))
                cr.set_source_surface(surf, 0, 0)
                cr.paint()
                cr.restore()
            else:
                cr.set_source_rgba(0.16, 0.19, 0.28, 0.95)
                cr.fill_preserve()
                cr.set_source_rgba(0.82, 0.86, 0.96, 0.85)
                cr.set_line_width(1.8)
                cr.rectangle(13, 15, w - 26, h - 30)
                cr.stroke()
                cr.arc(20, 22, 2.5, 0, 6.2832)
                cr.fill()
                cr.move_to(15, h - 18)
                cr.line_to(24, h - 27)
                cr.line_to(30, h - 22)
                cr.line_to(35, h - 25)
                cr.line_to(w - 15, h - 18)
                cr.stroke()

            cr.reset_clip()
            cr.new_sub_path()
            cr.arc(w - r, r, r, -1.5708, 0)
            cr.arc(w - r, h - r, r, 0, 1.5708)
            cr.arc(r, h - r, r, 1.5708, 3.1416)
            cr.arc(r, r, r, 3.1416, 4.7124)
            cr.close_path()
            cr.set_source_rgba(1.0, 1.0, 1.0, 0.35)
            cr.set_line_width(1.5)
            cr.stroke()

        def _draw_shutter_button(self, widget, cr):
            w = widget.get_allocated_width()
            h = widget.get_allocated_height()
            cx, cy = w / 2.0, h / 2.0
            outer_r = min(w, h) / 2.0 - 3.0

            cr.arc(cx, cy, outer_r, 0, 6.2832)
            cr.set_source_rgb(0.95, 0.97, 1.0)
            cr.set_line_width(3.5)
            cr.stroke()

            if self.mode == "video":
                if self.engine.is_recording():
                    sz = 26.0
                    rx, ry = cx - sz / 2.0, cy - sz / 2.0
                    rad = 6.0
                    cr.new_sub_path()
                    cr.arc(rx + sz - rad, ry + rad, rad, -1.5708, 0)
                    cr.arc(rx + sz - rad, ry + sz - rad, rad, 0, 1.5708)
                    cr.arc(rx + rad, ry + sz - rad, rad, 1.5708, 3.1416)
                    cr.arc(rx + rad, ry + rad, rad, 3.1416, 4.7124)
                    cr.close_path()
                    cr.set_source_rgb(0.94, 0.27, 0.27)
                    cr.fill()
                else:
                    cr.arc(cx, cy, outer_r - 7.5, 0, 6.2832)
                    cr.set_source_rgb(0.94, 0.27, 0.27)
                    cr.fill()
            else:
                cr.arc(cx, cy, outer_r - 7.5, 0, 6.2832)
                if self.countdown_left > 0:
                    cr.set_source_rgb(0.43, 0.55, 1.0)
                else:
                    cr.set_source_rgb(0.96, 0.97, 1.0)
                cr.fill()

        def _draw_switch_button(self, widget, cr):
            w = widget.get_allocated_width()
            h = widget.get_allocated_height()
            cx, cy = w / 2.0, h / 2.0
            cr.arc(cx, cy, min(w, h) / 2.0 - 1.5, 0, 6.2832)
            cr.set_source_rgba(0.16, 0.19, 0.28, 0.92)
            cr.fill_preserve()
            cr.set_source_rgba(1.0, 1.0, 1.0, 0.22)
            cr.set_line_width(1.5)
            cr.stroke()

            cr.set_source_rgb(0.94, 0.96, 1.0)
            cr.set_line_width(2.2)
            cr.set_line_cap(cairo.LINE_CAP_ROUND)
            r = 12.0
            cr.arc(cx, cy, r, -2.5, -0.35)
            cr.stroke()
            cr.arc(cx, cy, r, 0.65, 2.8)
            cr.stroke()
            # Small arrowheads on both arcs.
            ax1, ay1 = cx + r * 0.94, cy - r * 0.34
            cr.move_to(ax1 - 5, ay1 - 2)
            cr.line_to(ax1, ay1)
            cr.line_to(ax1 - 1, ay1 - 5)
            ax2, ay2 = cx - r * 0.94, cy + r * 0.34
            cr.move_to(ax2 + 5, ay2 + 2)
            cr.line_to(ax2, ay2)
            cr.line_to(ax2 + 1, ay2 + 5)
            cr.stroke()

        def _draw_gallery(self, widget, cr):
            w = widget.get_allocated_width()
            h = widget.get_allocated_height()
            if self._gallery_bgr is not None:
                self._draw_image_contained(cr, w, h, self._gallery_bgr, top_pad=8, bottom_pad=8)
                return
            cr.set_source_rgb(0.043, 0.051, 0.078)
            cr.paint()
            cr.set_source_rgba(0.75, 0.80, 0.92, 0.80)
            cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
            cr.set_font_size(16)
            msg = "No photos yet"
            ext = cr.text_extents(msg)
            cr.move_to((w - ext.width) / 2.0, h / 2.0)
            cr.show_text(msg)

        def _sync_ui_labels(self):
            info = self.engine.active_camera
            self.cam_badge_btn.set_label(info.label if info else "No camera")
            if self._has_flash_led and info and info.is_back:
                self.flash_btn.show()
            else:
                self.flash_btn.hide()
                if self.torch_on:
                    self.torch_on = False
                    set_flash_led(False)

            if self.mode == "photo":
                self.res_btn.show()
                self.timer_btn.show()
            else:
                self.res_btn.hide()
                self.timer_btn.hide()

            self.switch_btn.set_visible(len(self.cameras) > 1 if hasattr(self, "cameras") else len(cameras) > 1)

            def set_active(btn, active):
                ctx = btn.get_style_context()
                if active:
                    ctx.add_class("cam-pill-active")
                else:
                    ctx.remove_class("cam-pill-active")

            set_active(self.flash_btn, self.torch_on)
            self.flash_btn.set_label("Flash On" if self.torch_on else "Flash")
            set_active(self.grid_btn, self.show_grid)
            set_active(self.timer_btn, self.timer_sec > 0)
            self.timer_btn.set_label("Timer %ds" % self.timer_sec if self.timer_sec > 0 else "Timer")
            set_active(self.res_btn, self.high_res)
            self.res_btn.set_label("Full" if self.high_res else "HD")

            p_ctx = self.photo_mode_btn.get_style_context()
            v_ctx = self.video_mode_btn.get_style_context()
            if self.mode == "photo":
                p_ctx.add_class("cam-mode-selected")
                v_ctx.remove_class("cam-mode-selected-video")
            else:
                p_ctx.remove_class("cam-mode-selected")
                v_ctx.add_class("cam-mode-selected-video")

            self.shutter_area.queue_draw()

        def _switch_camera(self):
            if self.countdown_left > 0 or len(cameras) <= 1:
                return
            self.torch_on = False
            set_flash_led(False)
            self.engine.cycle_camera()
            self._sync_ui_labels()

        def _toggle_flash(self):
            self.torch_on = not self.torch_on
            if not set_flash_led(self.torch_on):
                self.torch_on = False
                self._show_toast("Flash control unavailable")
            self._sync_ui_labels()

        def _toggle_grid(self):
            self.show_grid = not self.show_grid
            self._sync_ui_labels()
            self.view_area.queue_draw()

        def _cycle_timer(self):
            self.timer_sec = {0: 3, 3: 10, 10: 0}.get(self.timer_sec, 0)
            self._sync_ui_labels()

        def _toggle_res(self):
            self.high_res = not self.high_res
            self._sync_ui_labels()

        def _set_mode(self, mode):
            if self.engine.is_recording():
                return
            self.mode = mode
            self._sync_ui_labels()

        def _on_shutter(self):
            if self.mode == "video":
                if self.engine.is_recording():
                    path, frames = self.engine.stop_video()
                    self._sync_ui_labels()
                    if path:
                        self._show_toast("Saved %s (%d frames)" % (os.path.basename(path), frames))
                else:
                    try:
                        self.engine.start_video()
                        self._sync_ui_labels()
                    except Exception as exc:
                        self._show_toast(str(exc), 3.0)
                return

            if self.countdown_left > 0:
                if self._countdown_src is not None:
                    GLib.source_remove(self._countdown_src)
                    self._countdown_src = None
                self.countdown_left = 0
                self._sync_ui_labels()
                self.view_area.queue_draw()
                return

            if self.timer_sec > 0:
                self.countdown_left = self.timer_sec
                self._sync_ui_labels()
                self.view_area.queue_draw()
                self._countdown_src = GLib.timeout_add(1000, self._countdown_step)
                return

            self._take_photo_async()

        def _countdown_step(self):
            self.countdown_left -= 1
            if self.countdown_left > 0:
                self.view_area.queue_draw()
                return True
            self._countdown_src = None
            self._sync_ui_labels()
            self._take_photo_async()
            return False

        def _take_photo_async(self):
            self._flash_alpha = 0.72
            self.view_area.queue_draw()
            high_res = self.high_res

            def job():
                try:
                    path = self.engine.capture_photo(high_res=high_res)
                    GLib.idle_add(lambda: (self._after_photo_saved(path), False)[1])
                except Exception as exc:
                    msg = str(exc)
                    GLib.idle_add(lambda: (self._show_toast(msg, 3.0), False)[1])

            threading.Thread(target=job, daemon=True).start()

        def _after_photo_saved(self, path):
            self._refresh_thumbnail()
            self._show_toast("Saved " + os.path.basename(path))

        def _refresh_thumbnail(self):
            files = list_gallery_photos()
            self._thumb_bgr = None
            if files:
                img = cv2.imread(files[0])
                if img is not None:
                    h, w = img.shape[:2]
                    side = min(w, h)
                    x0 = (w - side) // 2
                    y0 = (h - side) // 2
                    crop = img[y0:y0 + side, x0:x0 + side]
                    self._thumb_bgr = cv2.resize(crop, (96, 96), interpolation=cv2.INTER_AREA)
            self.thumb_area.queue_draw()

        def _open_gallery(self):
            self._gallery_files = list_gallery_photos()
            self._gallery_idx = 0
            self._load_gallery_image()
            self.stack.set_visible_child_name("gallery")

        def _close_gallery(self):
            self.stack.set_visible_child_name("viewfinder")
            self._refresh_thumbnail()
            self.view_area.queue_draw()

        def _load_gallery_image(self):
            self._gallery_bgr = None
            n = len(self._gallery_files)
            if n == 0:
                self.gallery_title.set_text("Gallery (empty)")
                self.gallery_meta.set_text("")
                self.delete_btn.set_sensitive(False)
                self.prev_btn.set_sensitive(False)
                self.next_btn.set_sensitive(False)
                self.gallery_area.queue_draw()
                return
            self._gallery_idx = max(0, min(self._gallery_idx, n - 1))
            path = self._gallery_files[self._gallery_idx]
            img = cv2.imread(path)
            self._gallery_bgr = img
            self.gallery_title.set_text("%s · %d/%d" % (os.path.basename(path), self._gallery_idx + 1, n))
            if img is not None:
                h, w = img.shape[:2]
                kb = max(1, os.path.getsize(path) // 1024)
                self.gallery_meta.set_text("%dx%d · %d KB" % (w, h, kb))
            else:
                self.gallery_meta.set_text("Unreadable image")
            self.delete_btn.set_sensitive(True)
            self.prev_btn.set_sensitive(self._gallery_idx > 0)
            self.next_btn.set_sensitive(self._gallery_idx + 1 < n)
            self.gallery_area.queue_draw()

        def _step_gallery(self, delta):
            if not self._gallery_files:
                return
            self._gallery_idx = max(0, min(len(self._gallery_files) - 1, self._gallery_idx + delta))
            self._load_gallery_image()

        def _delete_current_photo(self):
            if not self._gallery_files:
                return
            path = self._gallery_files[self._gallery_idx]
            try:
                os.remove(path)
            except OSError:
                return
            self._gallery_files = list_gallery_photos()
            if self._gallery_idx >= len(self._gallery_files):
                self._gallery_idx = max(0, len(self._gallery_files) - 1)
            self._load_gallery_image()
            self._refresh_thumbnail()

        def _open_in_thunar(self):
            os.makedirs(PICTURE_DIR, exist_ok=True)
            try:
                subprocess.Popen(["thunar", PICTURE_DIR])
            except Exception:
                self._show_toast("Could not launch file manager")

        def _on_key_press(self, _win, ev):
            kv = ev.keyval
            page = self.stack.get_visible_child_name()
            if page == "gallery":
                if kv in (Gdk.KEY_Left, Gdk.KEY_Up):
                    self._step_gallery(-1)
                    return True
                if kv in (Gdk.KEY_Right, Gdk.KEY_Down):
                    self._step_gallery(1)
                    return True
                if kv == Gdk.KEY_Escape:
                    self._close_gallery()
                    return True
                return False

            if kv in (
                Gdk.KEY_space,
                Gdk.KEY_Return,
                Gdk.KEY_KP_Enter,
                Gdk.KEY_XF86AudioRaiseVolume,
                Gdk.KEY_XF86AudioLowerVolume,
            ):
                self._on_shutter()
                return True
            if kv in (Gdk.KEY_s, Gdk.KEY_S, Gdk.KEY_Tab):
                self._switch_camera()
                return True
            if kv in (Gdk.KEY_v, Gdk.KEY_V):
                self._set_mode("video" if self.mode == "photo" else "photo")
                return True
            if kv in (Gdk.KEY_g, Gdk.KEY_G):
                self._toggle_grid()
                return True
            if kv == Gdk.KEY_Escape:
                if self.engine.is_recording():
                    self._on_shutter()
                else:
                    self._on_close()
                return True
            return False

        def _on_close(self, *_args):
            if self._countdown_src is not None:
                GLib.source_remove(self._countdown_src)
                self._countdown_src = None
            self.engine.stop()
            Gtk.main_quit()
            return False

    win = CameraWindow()
    win.show_all()

    def _handle_sig(*_):
        GLib.idle_add(lambda: (win._on_close(), False)[1])
        return True

    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, _handle_sig)
    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM, _handle_sig)
    Gtk.main()
    return 0


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("--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)
    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_gui(cameras, initial_index=initial, open_gallery=args.open_gallery)


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