#!/usr/bin/env python3
import argparse
import importlib
import locale
import math
import os
from pathlib import Path
import signal
import sys
import time
from dataclasses import dataclass, replace

try:
    import readline
except ImportError:
    readline = None


HEADER_LABELS = frozenset((
    "pinctrl-bcm2835",
    "pinctrl-bcm2711",
    "pinctrl-rp1",
))


class ControlError(Exception):
    pass


class Console:
    def __init__(self, color="auto"):
        self.color = color == "always" or (
            color == "auto" and sys.stdout.isatty()
            and os.environ.get("TERM") != "dumb"
            and "NO_COLOR" not in os.environ)
        self.dot = "o"
        if self.color:
            try:
                "\u25cf".encode(getattr(sys.stdout, "encoding", None) or "utf-8")
                self.dot = "\u25cf"
            except (UnicodeEncodeError, LookupError):
                pass

    def paint(self, text, style):
        if self.color:
            return "\033[{}m{}\033[0m".format(style, text)
        return text

    def title(self, text):
        print("\n" + self.paint(text, "1;36") + "\n")

    def section(self, text):
        print("  " + self.paint(text, "1"))

    def message(self, text, error=False):
        stream = sys.stderr if error else sys.stdout
        prefix = self.paint("Error: ", "31") if error else ""
        print("\n  " + prefix + text + "\n", file=stream, flush=True)

    def status(self, state, gpio):
        active = state == "on"
        style = "32" if active else "90"
        marker = self.paint(self.dot, style)
        label = self.paint(state.upper(), "1;" + style)
        print("\n  {} IR-cut {}\n    GPIO{}: {}\n".format(
            marker, label, gpio, "HIGH" if active else "LOW"), flush=True)


def english_detail(value):
    return str(value).encode("ascii", "backslashreplace").decode("ascii")


def checked(backend, result, operation):
    status = result if isinstance(result, int) else result[0]
    if status < 0:
        detail = english_detail(backend.error_text(status))
        raise ControlError("{}: {} (lgpio code {}).".format(
            operation, detail, status))
    return result


@dataclass(frozen=True)
class Chip:
    index: int
    lines: int
    name: str
    label: str
    aliases: tuple = ()

    @property
    def is_header(self):
        return self.label in HEADER_LABELS or self.name in HEADER_LABELS


def inspect_chips(backend, forced_index=None):
    if forced_index is None:
        indices = sorted({int(p.name[8:]) for p in Path("/dev").glob("gpiochip*")
                          if p.name[8:].isdigit()})
    else:
        indices = [forced_index]
    if not indices:
        raise ControlError(
            "No /dev/gpiochip devices were found. Run this script directly "
            "on a Raspberry Pi with Raspberry Pi OS Bookworm or Trixie. "
            "Containers must be given access to the correct GPIO device.")
    chips, failures = [], []
    identities = {}
    for index in indices:
        handle = None
        try:
            handle = checked(backend, backend.gpiochip_open(index),
                             "Cannot open /dev/gpiochip{}".format(index))
            info = checked(backend, backend.gpio_get_chip_info(handle),
                           "Cannot inspect /dev/gpiochip{}".format(index))
            identity = (("kernel", info[2], info[1], info[3]) if info[2]
                        else ("path", index))
            if identity in identities:
                position = identities[identity]
                chip = chips[position]
                chips[position] = replace(chip, aliases=chip.aliases + (index,))
            else:
                identities[identity] = len(chips)
                chips.append(Chip(index, info[1], info[2], info[3]))
        except (ControlError, OSError) as exc:
            failures.append(english_detail(exc))
        finally:
            if handle is not None and handle >= 0:
                checked(backend, backend.gpiochip_close(handle),
                        "Cannot close /dev/gpiochip{}".format(index))
    return chips, failures


def print_chips(chips, failures, console):
    console.title("GPIO Controllers")
    for chip in chips:
        kind = "HEADER CONTROLLER" if chip.is_header else "other controller"
        console.section("/dev/gpiochip{}".format(chip.index))
        print("    Label   {}\n    Lines   {}\n    Role    {}".format(
            english_detail(chip.label), chip.lines, kind))
        for alias in chip.aliases:
            print("    [ALIAS] /dev/gpiochip{}".format(alias))
        print()
    for failure in failures:
        console.message("Unavailable: " + failure)
    print("  No GPIO outputs have been changed.\n")


class IRcutController:
    def __init__(self, backend, chip, gpio, console):
        self.backend = backend
        self.chip = chip
        self.gpio = gpio
        self.handle = None
        self.claimed = False
        self.state = None
        self.console = console

    def start(self, state):
        self.handle = checked(
            self.backend, self.backend.gpiochip_open(self.chip.index),
            "Cannot open the selected GPIO controller")
        checked(self.backend,
                self.backend.gpio_claim_output(
                    self.handle, self.gpio, int(state == "on")),
                "Cannot claim BCM GPIO{} as an output".format(self.gpio))
        self.claimed = True
        self.state = state
        self.show_status()

    def set_state(self, state):
        checked(self.backend,
                self.backend.gpio_write(
                    self.handle, self.gpio, int(state == "on")),
                "Cannot write BCM GPIO{}".format(self.gpio))
        self.state = state
        self.show_status()

    def show_status(self):
        self.console.status(self.state, self.gpio)

    def close(self):
        failures = []
        had_claim = self.claimed
        if self.claimed:
            try:
                checked(self.backend,
                        self.backend.gpio_write(self.handle, self.gpio, 0),
                        "Cannot request LOW/OFF during shutdown")
                if self.state != "off":
                    self.state = "off"
                    self.show_status()
            except (ControlError, OSError) as exc:
                failures.append(english_detail(exc))
            try:
                checked(self.backend,
                        self.backend.gpio_free(self.handle, self.gpio),
                        "Cannot release the GPIO line")
            except (ControlError, OSError) as exc:
                failures.append(english_detail(exc))
            self.claimed = False
        if self.handle is not None:
            try:
                checked(self.backend, self.backend.gpiochip_close(self.handle),
                        "Cannot close the GPIO controller")
            except (ControlError, OSError) as exc:
                failures.append(english_detail(exc))
            self.handle = None
        for failure in failures:
            self.console.message(failure, error=True)
        if had_claim:
            if not failures:
                print("  OFF requested. GPIO released.")
            print("  The output level after release is not guaranteed.\n")
        return not failures


def print_instructions(gpio, chip, console):
    console.title("Camera IR-cut Controller")
    console.section("Connection")
    print("    Controller  /dev/gpiochip{}".format(chip.index))
    print("    Output      BCM GPIO{}{}\n".format(
        gpio, " (physical pin 11)" if gpio == 17 else ""))
    console.section("Setup")
    print("    The camera IR-cut DIP switch must be OFF.")
    print("    Connect BCM GPIO{} to the camera pad marked GPIO.".format(gpio))
    print("    Power down before wiring or changing the DIP switch.")


def interactive(controller):
    console = controller.console
    print("  Commands: on / off / toggle / status / help / quit")
    print("  Enter: status    Ctrl+C: exit")
    print("  Keep this session open to maintain the selected output.")
    print("  Exit requests OFF, then releases the GPIO.\n")
    while True:
        try:
            command = input("  IR-cut > ").strip().lower()
        except EOFError:
            console.message("End of input. Stopping.")
            return
        if command in ("on", "off"):
            controller.set_state(command)
        elif command == "toggle":
            controller.set_state("off" if controller.state == "on" else "on")
        elif command in ("", "status"):
            controller.show_status()
        elif command == "help":
            print()
            console.section("Commands")
            print("    on       Request IR-cut ON / GPIO HIGH")
            print("    off      Request IR-cut OFF / GPIO LOW")
            print("    toggle   Reverse the requested state")
            print("    status   Show the current request")
            print("    help     Show this command list")
            print("    quit     Request OFF, release the GPIO, and exit")
            print("\n    Status shows the requested state, not mechanical feedback.\n")
        elif command in ("quit", "exit", "q"):
            return
        else:
            console.message("Unknown command. Type help to see the available commands.")


def positive_seconds(value):
    try:
        seconds = float(value)
    except ValueError:
        raise argparse.ArgumentTypeError("duration must be a number") from None
    if not math.isfinite(seconds) or seconds <= 0:
        raise argparse.ArgumentTypeError("duration must be finite and greater than zero")
    return seconds


def gpio_number(value):
    try:
        gpio = int(value)
    except ValueError:
        raise argparse.ArgumentTypeError("GPIO must be an integer BCM number") from None
    if not 2 <= gpio <= 27:
        raise argparse.ArgumentTypeError("use a header BCM GPIO number from 2 to 27")
    return gpio


def chip_number(value):
    try:
        number = int(value)
    except ValueError:
        raise argparse.ArgumentTypeError("chip must be a non-negative integer, e.g. 0 or 4") from None
    if number < 0:
        raise argparse.ArgumentTypeError("chip must be a non-negative integer")
    return number


def parse_args(argv):
    parser = argparse.ArgumentParser(
        description="Control a camera IR-cut input: HIGH=ON, LOW=OFF.",
        epilog=("Examples:\n"
                "  python3 ircut_control.py\n"
                "  python3 ircut_control.py --state on\n"
                "  python3 ircut_control.py --state on --duration 10\n"
                "  python3 ircut_control.py --list-chips\n\n"
                "Keep the process running to maintain an output.\n"
                "Exit requests OFF, then releases the GPIO; its level after release\n"
                "is not guaranteed. Status shows a request, not filter feedback."),
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--gpio", type=gpio_number, default=17,
                        help="BCM GPIO number, not a physical pin number (default: 17)")
    parser.add_argument("--state", choices=("on", "off"),
                        help="hold this state; omit for an interactive session starting OFF")
    parser.add_argument("--duration", type=positive_seconds, metavar="SECONDS",
                        help="hold --state for this many seconds, then request OFF and exit")
    parser.add_argument("--chip", type=chip_number, metavar="N",
                        help="use /dev/gpiochipN; its label must identify a Pi header controller")
    parser.add_argument("--list-chips", action="store_true",
                        help="list controllers without claiming a GPIO, then exit")
    parser.add_argument("--color", choices=("auto", "always", "never"), default="auto",
                        help="terminal colors (default: auto; respects NO_COLOR)")
    args = parser.parse_args(argv)
    if args.duration is not None and args.state is None:
        parser.error("--duration requires --state on or --state off")
    if args.list_chips and (args.state is not None or args.duration is not None):
        parser.error("--list-chips cannot be combined with --state or --duration")
    if not args.list_chips and args.state is None and not sys.stdin.isatty():
        parser.error("interactive mode requires a terminal; use --state on or --state off")
    return args


def stop_requested(_signum, _frame):
    raise KeyboardInterrupt


def main(argv=None):
    os.environ["LANGUAGE"] = "C"
    try:
        locale.setlocale(locale.LC_MESSAGES, "C")
    except (AttributeError, locale.Error):
        pass
    args = parse_args(argv)
    console = Console(args.color)
    try:
        backend = importlib.import_module("lgpio")
    except ImportError:
        console.message("The lgpio Python module is not available.", error=True)
        print("Install it: sudo apt update && sudo apt install -y python3-lgpio",
              file=sys.stderr)
        print("Then run this script with /usr/bin/python3. For a virtual environment,",
              file=sys.stderr)
        print("create it with /usr/bin/python3 -m venv --system-site-packages .venv",
              file=sys.stderr)
        return 1
    backend.exceptions = False
    controller = None
    old_handlers = {}
    exit_code = 0
    try:
        for signum in (signal.SIGINT, signal.SIGTERM):
            old_handlers[signum] = signal.signal(signum, stop_requested)
        chips, failures = inspect_chips(backend, args.chip)
        if args.list_chips:
            print_chips(chips, failures, console)
            return 0 if chips else 1
        candidates = [chip for chip in chips if chip.is_header]
        if len(candidates) != 1:
            print_chips(chips, failures, console)
            raise ControlError(
                "Expected exactly one accessible Raspberry Pi header controller; "
                "found {}. Check device permissions and --list-chips. "
                "If several header controllers are present, select one with --chip N. "
                "Internal controllers and GPIO expanders are never selected.".format(
                    len(candidates)))
        chip = candidates[0]
        if args.gpio >= chip.lines:
            raise ControlError("The selected controller does not contain the requested GPIO.")
        print_instructions(args.gpio, chip, console)
        controller = IRcutController(backend, chip, args.gpio, console)
        controller.start(args.state or "off")
        if args.state is None:
            interactive(controller)
        elif args.duration is not None:
            console.message("Holding {} for {} seconds. Ctrl+C stops early.".format(
                args.state.upper(), args.duration))
            time.sleep(args.duration)
            console.message("The requested duration has elapsed.")
        else:
            console.message("Holding {} until Ctrl+C or SIGTERM.".format(
                args.state.upper()))
            while True:
                signal.pause()
    except KeyboardInterrupt:
        console.message("Stop requested. Cleaning up.")
    except (ControlError, OSError) as exc:
        console.message(english_detail(exc), error=True)
        print("  Help", file=sys.stderr)
        print("    Use --list-chips to inspect the controllers.", file=sys.stderr)
        print("    For access errors, check your gpio group membership and device",
              file=sys.stderr)
        print("    permissions. A temporary sudo /usr/bin/python3 run can diagnose access.",
              file=sys.stderr)
        print("    If the line is busy, stop its owner or disable the relevant overlay",
              file=sys.stderr)
        print("    only after confirming that it is not needed. Do not force the line.\n",
              file=sys.stderr)
        exit_code = 1
    finally:
        try:
            for signum in old_handlers:
                signal.signal(signum, signal.SIG_IGN)
            if controller is not None and not controller.close():
                exit_code = 1
        finally:
            for signum, previous in old_handlers.items():
                signal.signal(signum, previous)
    return exit_code


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