#!/usr/bin/env python3
"""Auto-rotate the Chandra KMS display from iio-sensor-proxy accelerometer events."""

import argparse
import ctypes
import os
import signal
import subprocess
import sys
import time

CHANDRA_CTL = "/usr/local/bin/chandra-ctl"
ORIENTATION_TO_DEG = {
    "normal": 0,
    "right-up": 90,
    "bottom-up": 180,
    "left-up": 270,
}
PR_SET_PDEATHSIG = 1


def parse_orientation(line: str) -> int | None:
    """Return display rotation degrees (0/90/180/270) from a monitor-sensor line."""
    text = line.strip()
    if "Accelerometer orientation changed:" in text:
        tail = text.split("Accelerometer orientation changed:", 1)[1].strip()
        val = tail.split()[0] if tail else ""
        return ORIENTATION_TO_DEG.get(val)
    if "orientation:" in text:
        part = text.split("orientation:", 1)[1].strip()
        val = part.split(",", 1)[0].rstrip(")").strip()
        return ORIENTATION_TO_DEG.get(val)
    return None


def set_parent_death_signal() -> None:
    """Request SIGTERM from the kernel when the parent compositor process exits."""
    try:
        libc = ctypes.CDLL("libc.so.6")
        libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM, 0, 0, 0)
    except OSError:
        pass


def parent_alive(pid: int) -> bool:
    """Return True while the tracked parent PID still exists."""
    try:
        os.kill(pid, 0)
        return True
    except ProcessLookupError:
        return False
    except PermissionError:
        return True


def wait_for_compositor(parent_pid: int, timeout_s: float = 15.0) -> bool:
    """Poll chandra-ctl ping until the compositor control socket responds or parent exits."""
    deadline = time.monotonic() + timeout_s
    while time.monotonic() < deadline:
        if os.getppid() != parent_pid or not parent_alive(parent_pid):
            return False
        res = subprocess.run(
            [CHANDRA_CTL, "ping"],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            check=False,
        )
        if res.returncode == 0:
            return True
        time.sleep(0.25)
    return False


def current_rotation() -> int | None:
    """Query current display rotation degrees via chandra-ctl rotate status."""
    res = subprocess.run(
        [CHANDRA_CTL, "rotate", "status"],
        stdout=subprocess.PIPE,
        stderr=subprocess.DEVNULL,
        text=True,
        check=False,
    )
    if res.returncode != 0:
        return None
    parts = res.stdout.strip().split()
    if len(parts) >= 2 and parts[0] == "ok":
        try:
            return int(parts[1])
        except ValueError:
            return None
    return None


def apply_rotation(deg: int) -> bool:
    """Apply display rotation in degrees via chandra-ctl rotate."""
    res = subprocess.run(
        [CHANDRA_CTL, "rotate", str(deg)],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
        check=False,
    )
    return res.returncode == 0


def main() -> int:
    """Watch monitor-sensor --accel and mirror orientation changes to Chandra."""
    parser = argparse.ArgumentParser(description="Chandra auto-rotate daemon")
    parser.add_argument("--parent-pid", type=int, default=os.getppid())
    args = parser.parse_args()
    parent_pid = args.parent_pid

    set_parent_death_signal()
    if os.getppid() != parent_pid:
        return 0

    if not wait_for_compositor(parent_pid):
        return 0

    proc = subprocess.Popen(
        ["monitor-sensor", "--accel"],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True,
        bufsize=1,
    )

    def stop_child(_signum: int, _frame: object) -> None:
        if proc.poll() is None:
            proc.terminate()
        raise SystemExit(0)

    signal.signal(signal.SIGTERM, stop_child)
    signal.signal(signal.SIGINT, stop_child)

    last_rot: int | None = None
    try:
        assert proc.stdout is not None
        for line in proc.stdout:
            if not parent_alive(parent_pid):
                break
            if "No accelerometer" in line or "Failed to claim accelerometer" in line:
                print(f"chandra-auto-rotate: {line.strip()}", file=sys.stderr, flush=True)
                break
            deg = parse_orientation(line)
            if deg is None or deg == last_rot:
                continue
            if last_rot is None and current_rotation() == deg:
                last_rot = deg
                continue
            apply_rotation(deg)
            last_rot = deg
    finally:
        if proc.poll() is None:
            proc.terminate()
            try:
                proc.wait(timeout=2)
            except subprocess.TimeoutExpired:
                proc.kill()
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
