#!/usr/bin/env python3
"""Configure an ACR1552U PICC interface from the command line.

Escape commands are sent with SCardControl(SCARD_CTL_CODE(3500)) on the PICC
interface, as specified in ACS ACR1552U Series Reference Manual V1.07 §6.0.
Pass any combination of options, or none to only read and print current values.

Commands used (section numbers from V1.07 unless noted):

    RF Control              E0 00 00 25 01 XX     §6.1.1   runtime
    Get PCD/PICC Status     E0 00 00 25 00        §6.1.2   read
    Get/Set Polling/ATR     E0 00 00 23 0X        §6.1.3-4 NV; initial config
    Get/Set PICC Polling    E0 00 01 20 …         §6.1.5-6 NV; initial config
    Get/Set Auto PPS        E0 00 00 24 0X        §6.1.7-8
    Read PICC Type          E0 00 00 35 00        §6.1.9   read
    Get/Set RF Power        E0 00 00 50 0X        §6.1.10-11 NV; self-resets
    Get/Set Sel. Suspend    E0 00 00 E5 0X        §6.1.12-13
    Get/Set Output Format   E0 00 00 90 …         §6.1.14  HID
    Get/Set UID Characters  E0 00 00 91 …         §6.1.14  HID
    Get/Set Keyboard Lang   E0 00 00 92 0X        §6.1.14  HID
    Get/Set Host Interface  E0 00 00 93 0X        §6.1.14  HID
    Get Firmware Version    E0 00 00 18 00        §6.2.1   read
    Get Serial Number       E0 00 00 33 00        §6.2.2   read
    Set S/N in USB Desc.    E0 00 00 F0 02 00 XX  §6.2.3
    Get/Set UI Behaviour    E0 00 00 21 0X        §6.2.9-10 NV; initial config

Apply / persistence notes from the manual:
    --power     After Set RF Power the reader resets once (§6.1.11).
    --pulse / --polling / --mifare-atr / --part4-atr / --picc-types / --ui-*
                Get/Set Polling/ATR, PICC Polling Type and UI Behaviour are
                "initial reader configuration" (§6.1.3, §6.1.5, §6.2.9).
                Unplug and replug after writing them.
    --pps       If the proposed speed is too high for the PICC or environment,
                the card becomes inaccessible; drop to a lower setting
                (§6.1.8 notes 1-2).
    --suspend   Cannot be enabled while the reader is in keyboard emulation,
                and vice versa (§6.1.13).
    --interface Switching to HID-only drops the PC/SC PICC interface until
                the reader is put back to CCID or HID+CCID.

Firmware gates (V1.07):
    RF Power            ACR1552U-M 1.03.03+ / ACM1552U-Y/Z 2.03.03+
    Selective Suspend   ACR1552U-M 1.05.00+ / ACR1552U-A 5.01.00+
                        / ACM1552U-Y/Z 2.05.00+
    HID output order 02h/04h   same FW as Selective Suspend
    UI bits 1 and 2     ACR1552U-M 1.03.05+ / ACM1552U-Y/Z 2.03.05+
    * RF Power percentages may have no effect due to hardware limitation.

Factory defaults (V1.07):
    RF Control          01h  RF On, with Polling
    Polling/ATR         8Bh  polling, RF-off interval, extra MIFARE ATR,
                             interval 00 (250 ms), Part 4 ATR
    PICC Polling Type   0705h  ISO14443A + ISO14443B + FeliCa
                               + Picopass (ISO14443B) + ISO15693
    Auto PPS            02h  424 kbps
    RF Power            00h  disable manual setting (hardware default)
    Selective Suspend   00h  disable
    Host Interface      01h  CCID only
    Keyboard language   00h  English
    UI Behaviour        0Fh  V1.07 (bits 0-3); V1.03 listed 09h (bits 0, 3)

Polling/ATR, UI, HID format and UID-delimiter options read-modify-write
the current NV value so unspecified flags are left unchanged. --picc-types
replaces the whole polling-type mask.

Examples:
    acr1552u_rf_config.py
    acr1552u_rf_config.py --power 100 --pulse 0
    acr1552u_rf_config.py --picc-types iso14443a,iso14443b,iso15693
    acr1552u_rf_config.py --pps 106 --mifare-atr on --part4-atr on
    acr1552u_rf_config.py --ui-access-led on --ui-presence-beep off
    acr1552u_rf_config.py --interface both --hid-mode hex --hid-case lower
    acr1552u_rf_config.py --tui
    acr1552u_rf_config.py --watch
"""

import argparse
import sys
import time

from smartcard.System import readers
from smartcard.scard import SCARD_CTL_CODE, SCARD_SHARE_DIRECT

# CCID PC_to_RDR_Escape. Manual §6.0: send all PICC escapes with this IOCTL
# on the PICC interface (not SAM).
ESCAPE = SCARD_CTL_CODE(3500)

# --- RF Power §6.1.10-11 ----------------------------------------------------
# 00h Disable manual RF Power setting (default)
# 01h 20%  02h 40%  03h 60%  04h 80%  05h 100%
POWER_BYTE = {0: 0x00, 20: 0x01, 40: 0x02, 60: 0x03, 80: 0x04, 100: 0x05}
BYTE_POWER = {v: k for k, v in POWER_BYTE.items()}

# --- RF Control §6.1.1 / PCD/PICC Status §6.1.2 -----------------------------
# "on" is kept as an alias of "nopoll" (RF On, without Polling).
RF_STATUS = {"off": 0x00, "poll": 0x01, "nopoll": 0x02, "on": 0x02}
PICC_STATUS = {
    0x00: "RF Off",
    0x01: "No PICC",
    0x02: "PICC Ready",
    0x03: "PICC Selected/Activated",
    0xFF: "Error",
}

# --- Polling/ATR Option §6.1.3-4 --------------------------------------------
# Bit 0 Enable Polling
# Bit 1 Enable RF Off Interval
# Bit 2 RFU
# Bit 3 Extra MIFARE type identification for Part 3 card in ATR
# Bit 4-5 RF Off Interval (see MS_SEL); ignored when bit 1 = 0 (No RF Off)
# Bit 6 RFU
# Bit 7 Part 4 ATR for SmartMX/JCOS card with MIFARE emulation
# Default 8Bh.
POLL_BIT_POLLING = 0x01
POLL_BIT_RF_OFF = 0x02
POLL_BIT_MIFARE_ATR = 0x08
POLL_BIT_PART4_ATR = 0x80
POLL_INTERVAL_MASK = 0x30
MS_SEL = {250: 0, 500: 1, 1000: 2, 2500: 3}
SEL_MS = {v: k for k, v in MS_SEL.items()}

# --- PICC Polling Type §6.1.5-6 (Byte 1, Byte 0; RFU bits must stay 0) ------
# Byte 1: bit0 ISO14443A  bit1 ISO14443B  bit2 FeliCa  bit4 Topaz
#         bit5 Innovatron  bit6 SRI/SRIX
# Byte 0: bit0 Picopass (ISO14443B)  bit1 Picopass (ISO15693)
#         bit2 ISO15693  bit3 CTS
# Default Byte1=07h Byte0=05h. Names are the manual Type/Technology labels.
PICC_TYPE_BITS = {
    "iso14443a": (1, 0),
    "iso14443b": (1, 1),
    "felica": (1, 2),
    "topaz": (1, 4),
    "innovatron": (1, 5),
    "sri": (1, 6),
    "picopass-b": (0, 0),
    "picopass-15693": (0, 1),
    "iso15693": (0, 2),
    "cts": (0, 3),
}
PICC_TYPE_ALIAS = {
    "type-a": "iso14443a",
    "type-b": "iso14443b",
    "srix": "sri",
    "sri/srix": "sri",
    "picopass-14443b": "picopass-b",
}
PICC_DEFAULT = (0x07, 0x05)
PICC_ALL = (0x77, 0x0F)

# --- Auto PPS §6.1.7-8 ------------------------------------------------------
# 00h 106 kbps (equal to No Auto PPS)  01h 212  02h 424 (default)  03h 848
PPS_BYTE = {106: 0x00, 212: 0x01, 424: 0x02, 848: 0x03}
BYTE_PPS = {v: k for k, v in PPS_BYTE.items()}

# --- PICC Type §6.1.9 -------------------------------------------------------
PICC_TYPE = {
    0xCC: "No PICC",
    0x04: "Topaz",
    0x10: "MIFARE",
    0x11: "FeliCa",
    0x20: "Type A, Part 4",
    0x23: "Type B, Part 4",
    0x25: "Innovatron",
    0x28: "SRIX",
    0x30: "PicoPass",
    0xFF: "Other",
}

# --- UI Behaviour §6.2.9-10 -------------------------------------------------
# Bit 0 Accessing (LED Fast Blinking)
# Bit 1 PICC Polling Status LED          (FW 1.03.05+ / 2.03.05+)
# Bit 2 PICC Activation Status LED       (FW 1.03.05+ / 2.03.05+)
# Bit 3 Presence Event (Short Buzzer Beep)
# Bit 4 Card Removal Event (Short Buzzer Beep)
# 1 = Enable, 0 = Disable. Default V1.07 = 0Fh.
UI_BITS = {
    "access-led": 0x01,
    "polling-led": 0x02,
    "activation-led": 0x04,
    "presence-beep": 0x08,
    "removal-beep": 0x10,
}

# --- Host Interface §6.1.14 -------------------------------------------------
IFACE_BYTE = {"hid": 0x00, "ccid": 0x01, "both": 0x02}
BYTE_IFACE = {
    0x00: "Only HID Keyboard",
    0x01: "Only CCID Reader",
    0x02: "HID Keyboard + CCID Reader",
}

# --- HID output format §6.1.14 ----------------------------------------------
# Letter Case, bits 7-4:  00x0 lowercase  00x1 uppercase
#                         000x 4-byte UID only  001x 4/7/8/10-byte UID
# Display Mode, bits 3-0: values below (manual names).
HID_MODE = {
    "hex": 0x0,
    "dec-byte": 0x1,
    "dec": 0x2,
    "6H-6H": 0x3,
    "8H-8H": 0x4,
    "10H-10H": 0x5,
    "14H-14H": 0x6,
    "20H-20H": 0x7,
    "6H-8D": 0x8,
    "6H-10D": 0x9,
    "8H-10D": 0xA,
    "10H-14D": 0xB,
    "2H4H-8D": 0xC,
    "14H-17D": 0xD,
}
BYTE_HID_MODE = {v: k for k, v in HID_MODE.items()}
HID_ORDER = {
    "default": 0x00,            # UID Byte 0 .. Byte N
    "reverse": 0x01,            # all card types reversed
    "reverse-14443-felica": 0x02,  # FW 1.05.00+ / 5.01.00+ / 2.05.00+
    "reverse-15693": 0x04,      # same FW gate
}
BYTE_HID_ORDER = {v: k for k, v in HID_ORDER.items()}

# USB HID Usage Tables (keyboard/keypad page) for UID delimiter characters.
# FFh = no character (§6.1.14). AZERTY only supports ; , . -
HID_CHAR = {
    "none": 0xFF,
    "enter": 0x28,
    "space": 0x2C,
    "hyphen": 0x2D,
    "minus": 0x2D,
    "semicolon": 0x33,
    "comma": 0x36,
    "period": 0x37,
    "dot": 0x37,
}

# --- Keyboard layout §6.1.14 ------------------------------------------------
KBD_BYTE = {"en": 0x00, "fr": 0x01, "lt": 0x03}
BYTE_KBD = {0x00: "English", 0x01: "French", 0x02: "Reserved", 0x03: "Lithuanian"}


# --- argparse helpers -------------------------------------------------------
def on_off(value):
    """Parse on/off-style flags. Used for bit enables in Polling/ATR, UI, etc."""
    v = value.lower()
    if v in ("on", "1", "true", "enable", "enabled"):
        return True
    if v in ("off", "0", "false", "disable", "disabled"):
        return False
    raise argparse.ArgumentTypeError("expected on or off, got %r" % value)


def hid_usage(value):
    """HID Usage Tables keyboard-page code (hex). Manual uses FFh for none.

    Bare digits are hex (28 == Enter), not decimal, matching the HID spec.
    """
    key = value.lower()
    if key in HID_CHAR:
        return HID_CHAR[key]
    raw = key[2:] if key.startswith("0x") else key
    try:
        n = int(raw, 16)
    except ValueError:
        raise argparse.ArgumentTypeError(
            "UID character %r: use none/enter/space/hyphen/semicolon/"
            "comma/period or a HID usage (28, 0x28)" % value)
    if not 0 <= n <= 0xFF:
        raise argparse.ArgumentTypeError("HID usage out of range: %r" % value)
    return n


def picc_types_arg(value):
    """Parse --picc-types into (Byte1, Byte0). Replaces the whole mask.

    Named lists and 'all' leave RFU bits 0. Hex 0xBBLL is rejected if RFU
    bits are set or if the mask would poll nothing.
    """
    raw = value.strip()
    if raw.lower() == "default":
        return PICC_DEFAULT
    if raw.lower() == "all":
        return PICC_ALL
    if raw.lower().startswith("0x"):
        n = int(raw, 16)
        if n > 0xFFFF:
            raise argparse.ArgumentTypeError(
                "PICC type mask %s is wider than 2 bytes" % raw)
        byte1, byte0 = (n >> 8) & 0xFF, n & 0xFF
        if byte1 & ~0x77 or byte0 & ~0x0F:
            raise argparse.ArgumentTypeError(
                "PICC type mask %s has RFU bits set (Byte1 bits 3+7 and "
                "Byte0 bits 4-7 must be 0)" % raw)
        if byte1 == 0 and byte0 == 0:
            raise argparse.ArgumentTypeError(
                "PICC type mask %s enables no card types" % raw)
        return (byte1, byte0)
    byte1, byte0 = 0, 0
    seen = False
    for token in raw.split(","):
        name = token.strip().lower()
        if not name:
            continue
        name = PICC_TYPE_ALIAS.get(name, name)
        if name not in PICC_TYPE_BITS:
            raise argparse.ArgumentTypeError(
                "unknown PICC type %r (see --help)" % token.strip())
        which, bit = PICC_TYPE_BITS[name]
        if which:
            byte1 |= 1 << bit
        else:
            byte0 |= 1 << bit
        seen = True
    if not seen:
        raise argparse.ArgumentTypeError(
            "PICC type list is empty; use named types, default, all, or 0xBBLL")
    return (byte1, byte0)


# --- PC/SC ------------------------------------------------------------------
def _connect_direct(timeout=15.0):
    """Open the first PICC interface in direct mode (no card required).

    Retries because Set RF Power resets the reader and the PICC name
    disappears for a few seconds. SAM slots contain "SAM", not "PICC".
    """
    deadline = time.time() + timeout
    last = None
    while time.time() < deadline:
        try:
            for r in readers():
                if "PICC" in str(r):
                    conn = r.createConnection()
                    conn.connect(mode=SCARD_SHARE_DIRECT)
                    return conn
        except Exception as e:
            last = e
        time.sleep(0.25)
    raise RuntimeError("ACR1552U PICC reader unavailable (resetting?): %s" % last)


def _control(conn, apdu):
    """SCardControl on an already-open connection. None if the IOCTL fails."""
    try:
        r = conn.control(ESCAPE, apdu)
        return list(r) if r else []
    except Exception:
        return None


def escape(apdu, timeout=15.0):
    """Send one escape APDU and disconnect. None means the control call failed
    (unsupported command, busy, or the device dropped during a self-reset).
    """
    conn = _connect_direct(timeout)
    try:
        return _control(conn, apdu)
    finally:
        try:
            conn.disconnect()
        except Exception:
            pass


def payload(r):
    """Return data bytes after the ACR escape header, if present.

    ACS replies are E1 00 00 00 Le [data]. pyscard may already have stripped
    that prefix, so only treat the buffer as a header when the first four
    bytes match and Le fits. A bare serial that happens to start with 0xE1
    must not be sliced.
    """
    if not r:
        return None
    r = list(r)
    if (len(r) >= 5
            and r[0] in (0xE0, 0xE1)
            and r[1] == 0x00
            and r[2] == 0x00
            and r[3] == 0x00
            and r[4] <= len(r) - 5):
        return r[5:5 + r[4]]
    return r


def last_byte(r):
    """First data byte of a 1-byte Get. Trailing 90 00 (if present) is ignored."""
    data = payload(r)
    if not data:
        return None
    if len(data) >= 3 and data[-2:] == [0x90, 0x00]:
        data = data[:-2]
    return data[0] if data else None


# --- get / set --------------------------------------------------------------
# APDUs are Class INS P1 P2 Lc [data]. Get uses Lc/Le 00h; Set uses 01h/02h/03h.
# One table in V1.07 lists Set RF Power as E0 00 01 50 01; Get and the original
# working script both use P1=00 (E0 00 00 50). Keep P1=00.

def get_firmware():
    """§6.2.1 E0 00 00 18 00 — ASCII firmware string, e.g. ACR1552 R FW 1.04.00."""
    data = payload(escape([0xE0, 0x00, 0x00, 0x18, 0x00]))
    if not data:
        return None
    return "".join(chr(b) for b in data if 32 <= b < 127)


def get_serial():
    """§6.2.2 E0 00 00 33 00 — raw serial bytes (often ASCII)."""
    data = payload(escape([0xE0, 0x00, 0x00, 0x33, 0x00]))
    if not data:
        return None
    return bytes(data)


def get_rf_status():
    """§6.1.2 Get PCD/PICC Status. Not RF Control; there is no Get for §6.1.1."""
    return last_byte(escape([0xE0, 0x00, 0x00, 0x25, 0x00]))


def set_rf_control(status):
    """§6.1.1 runtime RF Off / On+poll / On without poll. Lost on reader reset."""
    return escape([0xE0, 0x00, 0x00, 0x25, 0x01, status])


def get_polling_byte():
    """§6.1.3 initial-config NV register (polling, RF-off, ATR bits)."""
    return last_byte(escape([0xE0, 0x00, 0x00, 0x23, 0x00]))


def set_polling_byte(reg):
    """§6.1.4. Takes effect after unplug/replug."""
    return escape([0xE0, 0x00, 0x00, 0x23, 0x01, reg])


def get_picc_types():
    """§6.1.5 — (Byte1, Byte0). Example 07 05 = default families."""
    data = payload(escape([0xE0, 0x00, 0x01, 0x20, 0x00]))
    if not data or len(data) < 2:
        return None
    return (data[0], data[1])


def set_picc_types(byte1, byte0):
    """§6.1.6 E0 00 01 20 02 Byte1 Byte0. P1=01 unlike most other escapes."""
    return escape([0xE0, 0x00, 0x01, 0x20, 0x02, byte1, byte0])


def get_auto_pps():
    """§6.1.7 — (max speed, current speed). Times out on some A* firmware."""
    data = payload(escape([0xE0, 0x00, 0x00, 0x24, 0x00]))
    if not data:
        return None
    if len(data) >= 2:
        return (data[0], data[1])
    return (data[0], None)


def set_auto_pps(max_speed):
    """§6.1.8. Too-high Max Speed can make the PICC inaccessible."""
    return escape([0xE0, 0x00, 0x00, 0x24, 0x01, max_speed])


def get_picc_type():
    """§6.1.9 — (type, status) of the card in the field, or CCh / 01h if none."""
    data = payload(escape([0xE0, 0x00, 0x00, 0x35, 0x00]))
    if not data or len(data) < 2:
        return None
    return (data[0], data[1])


def get_power_byte():
    """§6.1.10. Needs FW 1.03.03+ / 2.03.03+."""
    return last_byte(escape([0xE0, 0x00, 0x00, 0x50, 0x00]))


def set_power_byte(byte):
    """§6.1.11. Reader resets once after this write."""
    return escape([0xE0, 0x00, 0x00, 0x50, 0x01, byte])


def get_suspend():
    """§6.1.12. None if FW < 1.05.00 (transaction error on this command)."""
    return last_byte(escape([0xE0, 0x00, 0x00, 0xE5, 0x00]))


def set_suspend(byte):
    """§6.1.13 00h disable / 01h enable. Illegal in keyboard-emulation mode."""
    return escape([0xE0, 0x00, 0x00, 0xE5, 0x01, byte])


def get_ui():
    """§6.2.9 PICC UI Behaviour. Not valid on the SAM interface."""
    return last_byte(escape([0xE0, 0x00, 0x00, 0x21, 0x00]))


def set_ui(byte):
    """§6.2.10. Initial config; unplug/replug. Bits 1-2 need FW 1.03.05+."""
    return escape([0xE0, 0x00, 0x00, 0x21, 0x01, byte])


def get_output_format():
    """§6.1.14 — (format, order) for HID UID output."""
    data = payload(escape([0xE0, 0x00, 0x00, 0x90, 0x00]))
    if not data or len(data) < 2:
        return None
    return (data[0], data[1])


def set_output_format(fmt, order):
    return escape([0xE0, 0x00, 0x00, 0x90, 0x02, fmt, order])


def get_uid_chars():
    """§6.1.14 — (between, end, start) HID usages. FFh = no character."""
    data = payload(escape([0xE0, 0x00, 0x00, 0x91, 0x00]))
    if not data or len(data) < 3:
        return None
    return (data[0], data[1], data[2])  # between, end, start


def set_uid_chars(between, end, start):
    return escape([0xE0, 0x00, 0x00, 0x91, 0x03, between, end, start])


def get_kbd():
    """§6.1.14 keyboard layout: 00h EN, 01h FR, 03h LT."""
    return last_byte(escape([0xE0, 0x00, 0x00, 0x92, 0x00]))


def set_kbd(byte):
    return escape([0xE0, 0x00, 0x00, 0x92, 0x01, byte])


def get_interface():
    """§6.1.14 host interface: 00h HID, 01h CCID, 02h both."""
    return last_byte(escape([0xE0, 0x00, 0x00, 0x93, 0x00]))


def set_interface(byte):
    """00h HID-only removes this PC/SC PICC interface until set back."""
    return escape([0xE0, 0x00, 0x00, 0x93, 0x01, byte])


def set_usb_sn(enable):
    """§6.2.3 E0 00 00 F0 02 00 XX. Appears on the next USB enumeration."""
    return escape([0xE0, 0x00, 0x00, 0xF0, 0x02, 0x00, 0x01 if enable else 0x00])


# --- decode / read-modify-write ---------------------------------------------
def _flag(v, bit):
    return "on" if v & bit else "off"


def decode_polling(v):
    """Split the Polling/ATR byte into polling, pulse text, MIFARE ATR, Part4."""
    polling = _flag(v, POLL_BIT_POLLING)
    mifare = _flag(v, POLL_BIT_MIFARE_ATR)
    part4 = _flag(v, POLL_BIT_PART4_ATR)
    if v & POLL_BIT_RF_OFF:
        pulse = "on, %d ms" % SEL_MS.get((v >> 4) & 0x03, -1)
    else:
        pulse = "off (continuous)"
    return polling, pulse, mifare, part4


def decode_picc_types(byte1, byte0):
    """Named families whose bits are set. RFU bits are ignored."""
    names = []
    for name, (which, bit) in PICC_TYPE_BITS.items():
        val = byte1 if which else byte0
        if val & (1 << bit):
            names.append(name)
    return names or ["(none)"]


def decode_ui(v):
    """Map each UI Behaviour bit to on/off for the status table."""
    return {name: _flag(v, bit) for name, bit in UI_BITS.items()}


def decode_hid_format(fmt):
    # Bit 4 = case (00x1 upper), bit 5 = UID length (001x 4/7/8/10).
    case = "upper" if fmt & 0x10 else "lower"
    uid_len = "4/7/8/10-byte" if fmt & 0x20 else "4-byte only"
    mode = BYTE_HID_MODE.get(fmt & 0x0F, "0x%X" % (fmt & 0x0F))
    return case, uid_len, mode


def decode_hid_char(b):
    # Prefer the primary name when two aliases share a usage (minus/hyphen).
    for name, code in HID_CHAR.items():
        if code == b and name not in ("minus", "dot"):
            return name
    return "0x%02X" % b


def apply_polling_changes(reg, args):
    """Read-modify-write Polling/ATR bits. Unspecified flags stay as-is.

    pulse=0 only clears bit 1 (continuous field). A duration sets bit 1 and
    bits 4-5; V1.07 Case 1 ignores those interval bits when bit 1 is clear.
    """
    if args.polling is not None:
        if args.polling:
            reg |= POLL_BIT_POLLING
        else:
            reg &= ~POLL_BIT_POLLING
    if args.pulse is not None:
        if args.pulse == 0:
            reg &= ~POLL_BIT_RF_OFF
        else:
            reg |= POLL_BIT_RF_OFF
            reg = (reg & ~POLL_INTERVAL_MASK) | (MS_SEL[args.pulse] << 4)
    if args.mifare_atr is not None:
        if args.mifare_atr:
            reg |= POLL_BIT_MIFARE_ATR
        else:
            reg &= ~POLL_BIT_MIFARE_ATR
    if args.part4_atr is not None:
        if args.part4_atr:
            reg |= POLL_BIT_PART4_ATR
        else:
            reg &= ~POLL_BIT_PART4_ATR
    return reg


def apply_ui_changes(reg, args):
    """Read-modify-write UI Behaviour bits. Unspecified flags stay as-is."""
    mapping = {
        "ui_access_led": "access-led",
        "ui_polling_led": "polling-led",
        "ui_activation_led": "activation-led",
        "ui_presence_beep": "presence-beep",
        "ui_removal_beep": "removal-beep",
    }
    for attr, name in mapping.items():
        val = getattr(args, attr)
        if val is None:
            continue
        bit = UI_BITS[name]
        if val:
            reg |= bit
        else:
            reg &= ~bit
    return reg


def apply_hid_format(fmt, order, args):
    """RMW the HID format byte; only replace order when --hid-order is set."""
    if args.hid_case is not None:
        if args.hid_case == "upper":
            fmt |= 0x10
        else:
            fmt &= ~0x10
    if args.hid_uid_bytes is not None:
        if args.hid_uid_bytes == "all":
            fmt |= 0x20
        else:
            fmt &= ~0x20
    if args.hid_mode is not None:
        fmt = (fmt & 0xF0) | HID_MODE[args.hid_mode]
    if args.hid_order is not None:
        order = HID_ORDER[args.hid_order]
    return fmt, order


def apply_uid_chars(between, end, start, args):
    """Replace only the delimiter usages that were requested."""
    if args.uid_between is not None:
        between = args.uid_between
    if args.uid_end is not None:
        end = args.uid_end
    if args.uid_start is not None:
        start = args.uid_start
    return between, end, start


# --- CLI --------------------------------------------------------------------
def parse():
    """Build the CLI. Help text cites V1.07 bits, APDUs, defaults, and FW gates."""
    p = argparse.ArgumentParser(
        description="Configure ACR1552U PICC RF, polling, PPS, UI and HID.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=__doc__)

    rf = p.add_argument_group(
        "RF field",
        "§6.1.1 RF Control (runtime) and §6.1.10-11 RF Power (NV, self-reset).")
    rf.add_argument(
        "--power", type=int, choices=[0, 20, 40, 60, 80, 100],
        help="RF output power percent. 0 = 00h Disable manual RF Power "
             "setting (hardware default). 20/40/60/80/100 = 01h-05h. "
             "Reader resets once after Set RF Power. Firmware: ACR1552U-M "
             "1.03.03+, ACM1552U-Y/Z 2.03.03+. Percentage mode may have no "
             "effect due to hardware limitation.")
    rf.add_argument(
        "--rf", choices=["off", "poll", "nopoll", "on"],
        help="RF Control (§6.1.1): off=00h RF Off; poll=01h RF On, with "
             "Polling (default); nopoll=02h RF On, without Polling. "
             "'on' is an alias of nopoll. Runtime; there is no Get for "
             "this setting (E0 00 00 25 00 returns PCD/PICC Status).")

    atr = p.add_argument_group(
        "Polling / ATR option  [E0 00 00 23]",
        "§6.1.3-4 PICC Polling/ATR Option (1 byte). Initial reader "
        "configuration; unplug/replug after writing. Default 8Bh. "
        "Bit 2 and bit 6 are RFU.")
    atr.add_argument(
        "--polling", type=on_off, metavar="{on,off}",
        help="Bit 0 Enable Polling. 1 = detect tags during PICC polling, "
             "0 = skip.")
    atr.add_argument(
        "--pulse", type=int, choices=[0, 250, 500, 1000, 2500],
        help="RF-off interval. 0 clears bit 1 (Enable RF Off Interval) so "
             "the field stays on (V1.07 Case 1: No RF Off). 250/500/1000/"
             "2500 sets bit 1 and bits 4-5 (00/01/10/11) for USB Active "
             "(D0): 250, 500, 1000, 2500 ms.")
    atr.add_argument(
        "--mifare-atr", type=on_off, metavar="{on,off}",
        help="Bit 3 Enable extra MIFARE type identification for Part 3 "
             "card in ATR. 1 = detect, 0 = skip. Changes the ATR returned "
             "for MIFARE / SmartMX-with-MIFARE (see §5.3.8 footnote 2).")
    atr.add_argument(
        "--part4-atr", type=on_off, metavar="{on,off}",
        help="Bit 7 Enable Part 4 ATR for SmartMX/JCOS card with MIFARE "
             "emulation. 1 = detect, 0 = skip. See §5.3.8 footnote 2.")

    picc = p.add_argument_group(
        "PICC polling type  [E0 00 01 20]",
        "§6.1.5-6 two-byte bit mask (Byte 1, Byte 0). Initial reader "
        "configuration. 1 = Detect, 0 = Skip; RFU bits are written as 0. "
        "Default 0705h. Topaz, Innovatron, SRI/SRIX, Picopass ISO15693 and "
        "CTS are off by default to reduce polling time (§5.3.8).")
    picc.add_argument(
        "--picc-types", type=picc_types_arg, metavar="LIST",
        help="Comma-separated types, or 'default' (0705h), 'all' (defined "
             "bits only), or a 16-bit hex mask 0xBBLL (Byte1<<8|Byte0). "
             "Types: iso14443a, iso14443b, felica, topaz, innovatron, sri, "
             "picopass-b, picopass-15693, iso15693, cts.")

    pps = p.add_argument_group(
        "Auto PPS  [E0 00 00 24]",
        "§6.1.7-8. After a PICC is recognized the reader proposes Max Speed, "
        "then falls back if the card does not support it. Default 02h "
        "(424 kbps). 00h = 106 kbps, equal to No Auto PPS.")
    pps.add_argument(
        "--pps", type=int, choices=[106, 212, 424, 848],
        help="Maximum PCD-PICC connection speed in kbps (00h/01h/02h/03h). "
             "A PICC or environment that cannot meet the proposed speed "
             "becomes inaccessible; switch back to a lower setting if "
             "performance suffers.")

    sus = p.add_argument_group(
        "Selective suspend  [E0 00 00 E5]",
        "§6.1.12-13. 00h Disable (default), 01h Enable. Cannot be enabled "
        "in keyboard emulation mode. Firmware: ACR1552U-M 1.05.00+, "
        "ACR1552U-A 5.01.00+, ACM1552U-Y/Z 2.05.00+.")
    sus.add_argument(
        "--suspend", type=on_off, metavar="{on,off}",
        help="USB selective suspend: on=01h Enable, off=00h Disable.")

    ui = p.add_argument_group(
        "UI behaviour  [E0 00 00 21]",
        "§6.2.9-10 PICC UI Behaviour (1 byte bit mask). Initial reader "
        "configuration; not available on the SAM interface. 1 = Enable, "
        "0 = Disable. Default V1.07 = 0Fh. Bits 1-2 need FW 1.03.05+ / "
        "2.03.05+.")
    ui.add_argument(
        "--ui-access-led", type=on_off, metavar="{on,off}",
        help="Bit 0 Accessing (LED Fast Blinking) while a card is "
             "communicating.")
    ui.add_argument(
        "--ui-polling-led", type=on_off, metavar="{on,off}",
        help="Bit 1 PICC Polling Status LED (FW 1.03.05+ / 2.03.05+).")
    ui.add_argument(
        "--ui-activation-led", type=on_off, metavar="{on,off}",
        help="Bit 2 PICC Activation Status LED (FW 1.03.05+ / 2.03.05+).")
    ui.add_argument(
        "--ui-presence-beep", type=on_off, metavar="{on,off}",
        help="Bit 3 Presence Event (Short Buzzer Beep) when a card is tapped.")
    ui.add_argument(
        "--ui-removal-beep", type=on_off, metavar="{on,off}",
        help="Bit 4 Card Removal Event (Short Buzzer Beep).")

    hid = p.add_argument_group(
        "HID keyboard  [E0 00 00 90/91/92/93]",
        "§6.1.14 UID keyboard-emulation settings. Default host interface "
        "is 01h Only CCID Reader. Selective suspend cannot be on at the "
        "same time as keyboard emulation.")
    hid.add_argument(
        "--interface", choices=sorted(IFACE_BYTE),
        help="Host Interface: hid=00h Only HID Keyboard; ccid=01h Only "
             "CCID Reader (default); both=02h HID Keyboard + CCID Reader. "
             "hid removes the PICC PC/SC interface until changed back.")
    hid.add_argument(
        "--hid-case", choices=["lower", "upper"],
        help="Output Format bits 7-4 letter case: lower=00x0, upper=00x1.")
    hid.add_argument(
        "--hid-uid-bytes", choices=["4", "all"],
        help="Output Format bits 7-4 UID length: 4=000x Only Support 4 "
             "bytes UID; all=001x Support 4, 7, 8, 10 bytes UID.")
    hid.add_argument(
        "--hid-mode", choices=sorted(HID_MODE, key=lambda k: HID_MODE[k]),
        help="Output Format bits 3-0 Display Mode: hex=0h, dec-byte=1h "
             "(Dec byte by byte), dec=2h, then 6H-6H / 8H-8H / 10H-10H / "
             "14H-14H / 20H-20H / 6H-8D / 6H-10D / 8H-10D / 10H-14D / "
             "2H4H-8D / 14H-17D (3h-Dh).")
    hid.add_argument(
        "--hid-order", choices=sorted(HID_ORDER, key=lambda k: HID_ORDER[k]),
        help="Output Order: default=00h UID Byte 0..N; reverse=01h all "
             "types reversed; reverse-14443-felica=02h; reverse-15693=04h. "
             "02h and 04h need FW 1.05.00+ / 5.01.00+ / 2.05.00+.")
    hid.add_argument(
        "--uid-start", type=hid_usage, metavar="CHAR",
        help="Character at the start of UID output (HID usage, hex). "
             "none/FF = no character. Names: none, enter, space, hyphen, "
             "semicolon, comma, period.")
    hid.add_argument(
        "--uid-between", type=hid_usage, metavar="CHAR",
        help="Character between each UID byte (HID usage, hex). FF = none. "
             "On AZERTY only ; , . - are supported; 0 and Backspace are not.")
    hid.add_argument(
        "--uid-end", type=hid_usage, metavar="CHAR",
        help="Character at the end of UID output (HID usage, hex). FF = none.")
    hid.add_argument(
        "--kbd", choices=sorted(KBD_BYTE),
        help="Keyboard Layout Language: en=00h English (default), "
             "fr=01h French, lt=03h Lithuanian. 02h is Reserved.")

    other = p.add_argument_group("Other")
    other.add_argument(
        "--usb-sn", type=on_off, metavar="{on,off}",
        help="Set S/N in USB Descriptor (§6.2.3): off=00h Disable, "
             "on=01h Enable. Takes effect on the next USB enumeration.")
    other.add_argument(
        "--tui", action="store_true",
        help="Interactive terminal UI (curses). PICC status and type refresh "
             "when a card is presented. Ignores other write flags.")
    other.add_argument(
        "--watch", action="store_true",
        help="After the status dump, keep reading PCD/PICC Status and PICC "
             "Type until Ctrl+C so a presented card is shown.")
    return p.parse_args()


def polling_changed(args):
    """True if any Polling/ATR flag was requested (triggers a Get then RMW)."""
    return any(v is not None for v in (
        args.polling, args.pulse, args.mifare_atr, args.part4_atr))


def ui_changed(args):
    """True if any UI Behaviour bit was requested (Get then RMW)."""
    return any(v is not None for v in (
        args.ui_access_led, args.ui_polling_led, args.ui_activation_led,
        args.ui_presence_beep, args.ui_removal_beep))


def hid_format_changed(args):
    """True if any HID format/order field was requested (Get then RMW)."""
    return any(v is not None for v in (
        args.hid_case, args.hid_uid_bytes, args.hid_mode, args.hid_order))


def uid_chars_changed(args):
    """True if any UID delimiter was requested (Get then RMW)."""
    return any(v is not None for v in (
        args.uid_start, args.uid_between, args.uid_end))


def _warn_print(msg):
    print(msg, file=sys.stderr)


def apply(args, warn=None):
    """Write only the args that are not None. Bit-fields are RMW.

    Order matters: NV first, then interface (except hid-only), then RF Power
    (self-reset), then runtime RF Control so --rf survives the reset.
    HID-only is applied by the caller after the status dump.
    warn= lets the TUI collect messages instead of printing to stderr.
    """
    need_replug = False
    w = warn or _warn_print

    if polling_changed(args):
        cur = get_polling_byte()
        if cur is None:
            w("warning: could not read Polling/ATR; not writing "
              "(refusing to overwrite unread bits)")
        else:
            set_polling_byte(apply_polling_changes(cur, args))
            need_replug = True

    # --picc-types replaces the whole mask; it is not a bit-wise merge.
    if args.picc_types is not None:
        set_picc_types(*args.picc_types)
        need_replug = True

    if args.pps is not None:
        set_auto_pps(PPS_BYTE[args.pps])

    if ui_changed(args):
        cur = get_ui()
        if cur is None:
            w("warning: could not read UI Behaviour; not writing "
              "(refusing to overwrite unread bits)")
        else:
            set_ui(apply_ui_changes(cur, args))
            need_replug = True

    if args.suspend is not None:
        if get_suspend() is None:
            w("warning: Selective Suspend is not supported on this "
              "firmware (needs ACR1552U-M 1.05.00+ / ACR1552U-A 5.01.00+ "
              "/ ACM1552U-Y/Z 2.05.00+); not writing.")
        else:
            set_suspend(0x01 if args.suspend else 0x00)

    if hid_format_changed(args):
        cur = get_output_format()
        if cur is None:
            w("warning: could not read HID output format; not writing "
              "(refusing to overwrite unread bits)")
        else:
            fmt, order = apply_hid_format(cur[0], cur[1], args)
            set_output_format(fmt, order)

    if uid_chars_changed(args):
        cur = get_uid_chars()
        if cur is None:
            w("warning: could not read UID characters; not writing "
              "(refusing to overwrite unread bits)")
        else:
            between, end, start = apply_uid_chars(cur[0], cur[1], cur[2], args)
            set_uid_chars(between, end, start)

    if args.kbd is not None:
        set_kbd(KBD_BYTE[args.kbd])

    if args.usb_sn is not None:
        set_usb_sn(args.usb_sn)

    # HID-only removes the PICC PC/SC interface; apply it after report().
    if args.interface is not None and args.interface != "hid":
        set_interface(IFACE_BYTE[args.interface])

    # RF Power resets the reader (§6.1.11), so apply it before runtime RF
    # Control. _connect_direct() waits for the PICC interface to return.
    if args.power is not None:
        set_power_byte(POWER_BYTE[args.power])

    if args.rf is not None:
        set_rf_control(RF_STATUS[args.rf])

    return need_replug


def _hx(value, width=2):
    """Hex cell for the dump table. Empty when the Get failed."""
    if value is None:
        return ""
    return "0x%0*X" % (width, value)


def _serial_text(sn):
    """Print serial as ASCII when it is printable; otherwise hex."""
    if sn is None:
        return "?"
    try:
        if all(32 <= c < 127 for c in sn):
            return sn.decode("ascii")
    except Exception:
        pass
    return sn.hex()


def format_pcd_status(rf):
    """Decode Get PCD/PICC Status (§6.1.2). Returns (text, hex)."""
    if rf is None:
        return "?", ""
    return PICC_STATUS.get(rf, "?"), _hx(rf)


def format_picc_type(picc):
    """Decode Read PICC Type (§6.1.9). Returns type text, status text, hexes."""
    if picc is None:
        return "?", "?", "", ""
    typ, st = picc
    return (
        PICC_TYPE.get(typ, _hx(typ)),
        PICC_STATUS.get(st, _hx(st)),
        _hx(typ),
        _hx(st),
    )


LIVE_PICC_POLL_S = 0.4


def live_picc_rows(timeout=0.6):
    """Re-read only PCD/PICC Status and PICC Type on one connection.

    Used by the TUI and --watch so a presented card shows up without
    re-fetching NV settings. None if the PICC interface is unreachable.
    """
    try:
        conn = _connect_direct(timeout)
    except RuntimeError:
        return None
    try:
        rf = last_byte(_control(conn, [0xE0, 0x00, 0x00, 0x25, 0x00]))
        data = payload(_control(conn, [0xE0, 0x00, 0x00, 0x35, 0x00]))
    finally:
        try:
            conn.disconnect()
        except Exception:
            pass
    # Keep the last good snapshot if either Get glitches.
    if rf is None or not data or len(data) < 2:
        return None
    picc = (data[0], data[1])
    pcd_s, pcd_h = format_pcd_status(rf)
    typ_s, st_s, typ_h, st_h = format_picc_type(picc)
    return [
        ("pcd/picc status", pcd_s, pcd_h, "E0 00 00 25", None),
        ("picc type", typ_s, typ_h, "E0 00 00 35", None),
        ("picc status", st_s, st_h, "E0 00 00 35", None),
    ]


def merge_live_picc(rows, live):
    """Replace live PICC rows in place. Returns (rows, changed)."""
    if not rows or not live:
        return rows, False
    by = {r[0]: r for r in live}
    changed = False
    out = []
    for row in rows:
        nxt = by.get(row[0])
        if nxt is not None and row != nxt:
            changed = True
            out.append(nxt)
        else:
            out.append(row)
    return out, changed


def watch_picc():
    """CLI loop: print PCD/PICC and PICC Type whenever they change."""
    print("Watching PICC field (Ctrl+C to stop)…")
    last = None
    try:
        while True:
            live = live_picc_rows()
            if live is not None and live != last:
                for label, value, hx, cmd, _edit in live:
                    print("  %-16s  %-24s  %-8s  %s" % (label, value, hx, cmd))
                print()
                last = live
            time.sleep(LIVE_PICC_POLL_S)
    except KeyboardInterrupt:
        print()


def print_table(headers, rows):
    """Fixed-width ASCII table. Column widths follow the longest cell."""
    cols = list(zip(headers, *rows)) if rows else [(h,) for h in headers]
    widths = [max(len(str(cell)) for cell in col) for col in cols]
    border = "+-" + "-+-".join("-" * w for w in widths) + "-+"

    def line(cells):
        return "| " + " | ".join(
            str(cell).ljust(w) for cell, w in zip(cells, widths)) + " |"

    print(border)
    print(line(headers))
    print(border)
    for row in rows:
        print(line(row))
    print(border)


def collect_status():
    """Read every Get we use and return table rows for the CLI and TUI.

    Each row is (label, value, hex, command, edit_key). edit_key is the
    blank_args() field the TUI writes, or None for live/read-only status
    (firmware, serial, PCD/PICC status, current PPS, PICC type).
    """
    fw = get_firmware()
    sn = get_serial()
    pwr = get_power_byte()
    pol = get_polling_byte()
    types = get_picc_types()
    pps = get_auto_pps()
    sus = get_suspend()
    ui = get_ui()
    iface = get_interface()
    hid = get_output_format()
    uidc = get_uid_chars()
    kbd = get_kbd()
    rf = get_rf_status()
    picc = get_picc_type()

    if pwr in BYTE_POWER:
        pwr_s = "disable manual" if pwr == 0x00 else "%d%%" % BYTE_POWER[pwr]
    else:
        pwr_s = "?"

    if pps is None:
        pps_max, pps_cur = "?", "?"
        pps_hex = pps_cur_hex = ""
    else:
        mx, cur = pps
        pps_max = "%d kbps" % BYTE_PPS[mx] if mx in BYTE_PPS else _hx(mx)
        if cur is None:
            pps_cur = "?"
        elif cur in BYTE_PPS:
            pps_cur = "%d kbps" % BYTE_PPS[cur]
        else:
            pps_cur = _hx(cur)
        pps_hex = _hx(mx)
        pps_cur_hex = _hx(cur)

    if hid is None:
        hid_case = hid_uid = hid_mode = hid_order = "?"
        hid_fmt_hex = hid_order_hex = ""
    else:
        fmt, order = hid
        hid_case, hid_uid, hid_mode = decode_hid_format(fmt)
        hid_order = BYTE_HID_ORDER.get(order, _hx(order))
        hid_fmt_hex = _hx(fmt)
        hid_order_hex = _hx(order)

    if uidc is None:
        uid_start = uid_between = uid_end = "?"
        uid_start_hex = uid_between_hex = uid_end_hex = ""
    else:
        between, end, start = uidc
        uid_start, uid_between, uid_end = (
            decode_hid_char(start), decode_hid_char(between),
            decode_hid_char(end))
        uid_start_hex, uid_between_hex, uid_end_hex = (
            _hx(start), _hx(between), _hx(end))

    if pol is None:
        polling = pulse = mifare = part4 = "?"
    else:
        polling, pulse, mifare, part4 = decode_polling(pol)

    if types is None:
        type_s, type_hex = "?", ""
    else:
        b1, b0 = types
        type_s = ",".join(decode_picc_types(b1, b0))
        type_hex = _hx((b1 << 8) | b0, 4)

    flags = decode_ui(ui) if ui is not None else None
    pcd_s, pcd_h = format_pcd_status(rf)
    picc_type, picc_st, picc_type_hex, picc_st_hex = format_picc_type(picc)

    def row(label, value, hx, cmd, edit=None):
        return (label, value, hx, cmd, edit)

    return [
        row("firmware", fw or "?", "", "E0 00 00 18"),
        row("serial", _serial_text(sn), "", "E0 00 00 33"),
        row("power", pwr_s, _hx(pwr), "E0 00 00 50", "power"),
        row("pcd/picc status", pcd_s, pcd_h, "E0 00 00 25"),
        # Polling/ATR is one NV byte; these four rows share that hex value.
        row("polling", polling, _hx(pol), "E0 00 00 23", "polling"),
        row("pulse", pulse, _hx(pol), "E0 00 00 23", "pulse"),
        row("mifare-atr", mifare, _hx(pol), "E0 00 00 23", "mifare_atr"),
        row("part4-atr", part4, _hx(pol), "E0 00 00 23", "part4_atr"),
        row("picc-types", type_s, type_hex, "E0 00 01 20", "picc_types"),
        row("auto-pps max", pps_max, pps_hex, "E0 00 00 24", "pps"),
        row("auto-pps current", pps_cur, pps_cur_hex, "E0 00 00 24"),
        row("suspend",
            "unsupported (needs FW 1.05.00+)" if sus is None
            else ("enable" if sus else "disable"),
            _hx(sus), "E0 00 00 E5", "suspend" if sus is not None else None),
        row("ui access-led",
            flags["access-led"] if flags else "?", _hx(ui), "E0 00 00 21",
            "ui_access_led"),
        row("ui polling-led",
            flags["polling-led"] if flags else "?", _hx(ui), "E0 00 00 21",
            "ui_polling_led"),
        row("ui activation-led",
            flags["activation-led"] if flags else "?", _hx(ui), "E0 00 00 21",
            "ui_activation_led"),
        row("ui presence-beep",
            flags["presence-beep"] if flags else "?", _hx(ui), "E0 00 00 21",
            "ui_presence_beep"),
        row("ui removal-beep",
            flags["removal-beep"] if flags else "?", _hx(ui), "E0 00 00 21",
            "ui_removal_beep"),
        row("interface",
            BYTE_IFACE.get(iface, "?") if iface is not None else "?",
            _hx(iface), "E0 00 00 93", "interface"),
        row("hid-case", hid_case, hid_fmt_hex, "E0 00 00 90", "hid_case"),
        row("hid-uid-bytes", hid_uid, hid_fmt_hex, "E0 00 00 90",
            "hid_uid_bytes"),
        row("hid-mode", hid_mode, hid_fmt_hex, "E0 00 00 90", "hid_mode"),
        row("hid-order", hid_order, hid_order_hex, "E0 00 00 90", "hid_order"),
        row("uid-start", uid_start, uid_start_hex, "E0 00 00 91", "uid_start"),
        row("uid-between", uid_between, uid_between_hex, "E0 00 00 91",
            "uid_between"),
        row("uid-end", uid_end, uid_end_hex, "E0 00 00 91", "uid_end"),
        row("kbd",
            BYTE_KBD.get(kbd, "?") if kbd is not None else "?",
            _hx(kbd), "E0 00 00 92", "kbd"),
        row("picc type", picc_type, picc_type_hex, "E0 00 00 35"),
        row("picc status", picc_st, picc_st_hex, "E0 00 00 35"),
    ]


def report():
    """CLI dump: drop the TUI edit_key so the table is Setting/Value/Hex/Command."""
    rows = [(r[0], r[1], r[2], r[3]) for r in collect_status()]
    print_table(("Setting", "Value", "Hex", "Command"), rows)


def blank_args():
    """Namespace with every apply() field set to None (TUI writes one at a time)."""
    names = (
        "polling", "pulse", "mifare_atr", "part4_atr", "picc_types", "pps",
        "ui_access_led", "ui_polling_led", "ui_activation_led",
        "ui_presence_beep", "ui_removal_beep", "suspend", "hid_case",
        "hid_uid_bytes", "hid_mode", "hid_order", "uid_start", "uid_between",
        "uid_end", "kbd", "usb_sn", "interface", "power", "rf",
    )
    return argparse.Namespace(**{n: None for n in names})


def run_tui():
    """Curses front end. Same Gets/Sets as the CLI; no extra dependencies."""
    import curses
    curses.wrapper(_tui_main)


def _tui_clip(stdscr, y, x, text, attr=0):
    """Write one line without raising if it hits the window edge."""
    import curses
    h, w = stdscr.getmaxyx()
    if y < 0 or y >= h or x >= w:
        return
    text = text[: max(0, w - x - 1)]
    try:
        stdscr.addstr(y, x, text, attr)
    except curses.error:
        pass


def _tui_center_box(stdscr, lines, title, selected=None):
    """Modal list box. selected= highlights that row."""
    import curses
    h, w = stdscr.getmaxyx()
    inner = max(len(title) + 4, max((len(s) for s in lines), default=0) + 4, 24)
    box_w = min(w - 2, inner)
    box_h = min(h - 2, len(lines) + 4)
    y0 = max(0, (h - box_h) // 2)
    x0 = max(0, (w - box_w) // 2)
    win = curses.newwin(box_h, box_w, y0, x0)
    try:
        win.bkgd(" ", curses.color_pair(4))
    except curses.error:
        pass
    win.box()
    try:
        win.addnstr(0, 2, " %s " % title, box_w - 6, curses.A_BOLD)
        for i, line in enumerate(lines[: box_h - 3]):
            attr = curses.A_REVERSE if selected == i else 0
            win.addnstr(i + 2, 2, line, box_w - 4, attr)
    except curses.error:
        pass
    win.refresh()
    return win


def _tui_pick(stdscr, title, labels, current=0):
    """Single-choice list. Returns the index, or None if cancelled."""
    import curses
    idx = max(0, min(current, len(labels) - 1))
    while True:
        _tui_center_box(stdscr, labels, title, selected=idx)
        ch = stdscr.getch()
        if ch in (curses.KEY_UP, ord("k")):
            idx = (idx - 1) % len(labels)
        elif ch in (curses.KEY_DOWN, ord("j")):
            idx = (idx + 1) % len(labels)
        elif ch in (27, ord("q")):
            return None
        elif ch in (10, 13, curses.KEY_ENTER):
            return idx


def _tui_confirm(stdscr, title, message):
    """Yes/no for destructive writes (RF Power reset, HID-only)."""
    pick = _tui_pick(stdscr, title, [message, "Cancel", "Confirm"], 1)
    return pick == 2


def _tui_checklist(stdscr, title, items, selected):
    """Multi-select for --picc-types. Returns chosen names, or None."""
    import curses
    flags = [c for _, c in items]
    names = [n for n, _ in items]
    idx = 0
    while True:
        lines = [
            ("[*] " if flags[i] else "[ ] ") + names[i]
            for i in range(len(names))
        ]
        lines.append("Space toggle   Enter apply   Esc cancel")
        _tui_center_box(stdscr, lines, title,
                        selected=idx if idx < len(names) else None)
        ch = stdscr.getch()
        if ch in (curses.KEY_UP, ord("k")):
            idx = (idx - 1) % len(names)
        elif ch in (curses.KEY_DOWN, ord("j")):
            idx = (idx + 1) % len(names)
        elif ch == ord(" "):
            flags[idx] = not flags[idx]
        elif ch in (27, ord("q")):
            return None
        elif ch in (10, 13, curses.KEY_ENTER):
            return [names[i] for i in range(len(names)) if flags[i]]


def _tui_help(stdscr):
    lines = [
        "Up/Down or j/k   move",
        "Enter            edit selected setting",
        "r                re-read reader",
        "q or Esc         quit",
        "",
        "pcd/picc status, picc type and picc status",
        "refresh when a card is presented.",
        "",
        "Read-only rows cannot be edited.",
        "Power reset and HID-only ask to confirm.",
        "Polling/ATR, PICC types and UI need a replug.",
    ]
    _tui_center_box(stdscr, lines, "Keys")
    stdscr.getch()


def _tui_apply(edit, value, warn):
    """Apply one TUI edit through apply(), then HID-only if requested."""
    args = blank_args()
    setattr(args, edit, value)
    replug = apply(args, warn=warn)
    notes = []
    if replug:
        notes.append("NV written -- unplug and replug for it to take effect.")
    if edit == "power":
        notes.append("RF Power written; reader self-resets once.")
    if edit == "interface" and value == "hid":
        set_interface(IFACE_BYTE["hid"])
        notes.append("HID-only set; this PC/SC PICC interface will disappear.")
    if edit == "suspend" and value:
        notes.append("Selective Suspend cannot be on with keyboard emulation.")
    return notes


def _tui_edit(stdscr, edit, current_value):
    """Modal picker for one setting. None means the user cancelled."""
    if edit in (
            "polling", "mifare_atr", "part4_atr", "suspend",
            "ui_access_led", "ui_polling_led", "ui_activation_led",
            "ui_presence_beep", "ui_removal_beep"):
        labels = ["off", "on"]
        cur = 1 if str(current_value).lower() in ("on", "enable") else 0
        pick = _tui_pick(stdscr, edit.replace("_", "-"), labels, cur)
        if pick is None:
            return None
        return labels[pick] == "on"

    if edit == "power":
        labels = ["0 disable manual", "20%", "40%", "60%", "80%", "100%"]
        vals = [0, 20, 40, 60, 80, 100]
        pick = _tui_pick(stdscr, "RF Power (resets reader)", labels, 0)
        if pick is None:
            return None
        if not _tui_confirm(stdscr, "Set RF Power",
                            "Reader will reset once. Continue?"):
            return None
        return vals[pick]

    if edit == "pulse":
        labels = ["0 continuous", "250 ms", "500 ms", "1000 ms", "2500 ms"]
        vals = [0, 250, 500, 1000, 2500]
        pick = _tui_pick(stdscr, "RF-off interval", labels, 0)
        return None if pick is None else vals[pick]

    if edit == "pps":
        labels = ["106 kbps (no Auto PPS)", "212 kbps", "424 kbps", "848 kbps"]
        vals = [106, 212, 424, 848]
        pick = _tui_pick(stdscr, "Auto PPS max", labels, 2)
        return None if pick is None else vals[pick]

    if edit == "picc_types":
        enabled = set()
        if current_value and current_value not in ("?", "(none)"):
            enabled = set(current_value.split(","))
        items = [(n, n in enabled) for n in PICC_TYPE_BITS]
        chosen = _tui_checklist(stdscr, "PICC polling types", items, enabled)
        if chosen is None:
            return None
        if not chosen:
            return None
        byte1 = byte0 = 0
        for name in chosen:
            which, bit = PICC_TYPE_BITS[name]
            if which:
                byte1 |= 1 << bit
            else:
                byte0 |= 1 << bit
        return (byte1, byte0)

    if edit == "interface":
        labels = ["ccid  Only CCID Reader",
                  "both  HID Keyboard + CCID",
                  "hid   Only HID Keyboard (loses PC/SC)"]
        vals = ["ccid", "both", "hid"]
        pick = _tui_pick(stdscr, "Host interface", labels, 0)
        if pick is None:
            return None
        if vals[pick] == "hid":
            if not _tui_confirm(
                    stdscr, "HID-only",
                    "PC/SC PICC access will disappear. Continue?"):
                return None
        return vals[pick]

    if edit == "hid_case":
        pick = _tui_pick(stdscr, "HID letter case", ["lower", "upper"],
                         1 if current_value == "upper" else 0)
        return None if pick is None else ("lower", "upper")[pick]

    if edit == "hid_uid_bytes":
        pick = _tui_pick(stdscr, "HID UID length",
                         ["4-byte only", "4/7/8/10-byte"],
                         1 if "7" in str(current_value) else 0)
        return None if pick is None else ("4", "all")[pick]

    if edit == "hid_mode":
        labels = sorted(HID_MODE, key=lambda k: HID_MODE[k])
        cur = labels.index(current_value) if current_value in labels else 0
        pick = _tui_pick(stdscr, "HID display mode", labels, cur)
        return None if pick is None else labels[pick]

    if edit == "hid_order":
        labels = sorted(HID_ORDER, key=lambda k: HID_ORDER[k])
        cur = labels.index(current_value) if current_value in labels else 0
        pick = _tui_pick(stdscr, "HID output order", labels, cur)
        return None if pick is None else labels[pick]

    if edit in ("uid_start", "uid_between", "uid_end"):
        labels = ["none", "enter", "space", "hyphen", "semicolon",
                  "comma", "period"]
        cur = labels.index(current_value) if current_value in labels else 0
        pick = _tui_pick(stdscr, edit.replace("_", "-"), labels, cur)
        return None if pick is None else HID_CHAR[labels[pick]]

    if edit == "kbd":
        labels = ["en English", "fr French", "lt Lithuanian"]
        vals = ["en", "fr", "lt"]
        pick = _tui_pick(stdscr, "Keyboard layout", labels, 0)
        return None if pick is None else vals[pick]

    return None


def _tui_main(stdscr):
    """Main TUI loop: draw table, edit on Enter, refresh on r, quit on q.

    getch() times out so PCD/PICC Status and PICC Type can be re-read
    while the UI is idle. Modals switch back to blocking input.
    """
    import curses
    poll_ms = int(LIVE_PICC_POLL_S * 1000)
    curses.curs_set(0)
    curses.use_default_colors()
    if curses.has_colors():
        curses.init_pair(1, curses.COLOR_CYAN, -1)
        curses.init_pair(2, curses.COLOR_YELLOW, -1)
        curses.init_pair(3, curses.COLOR_GREEN, -1)
        curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLUE)

    status = "Reading reader…"
    rows = []
    cursor = 0
    scroll = 0
    idle_hint = "Enter edit   r refresh   PICC live   ? help   q quit"

    def set_poll(on):
        stdscr.timeout(poll_ms if on else -1)

    def refresh_rows():
        nonlocal rows, status
        set_poll(False)
        status = "Reading…"
        _tui_draw(stdscr, rows, cursor, scroll, status)
        stdscr.refresh()
        try:
            rows = collect_status()
            status = idle_hint
        except Exception as e:
            rows = []
            status = "error: %s" % e
        set_poll(True)

    def poll_picc():
        nonlocal rows
        live = live_picc_rows(timeout=0.5)
        rows, changed = merge_live_picc(rows, live)
        return changed

    refresh_rows()
    need_draw = True

    while True:
        h, w = stdscr.getmaxyx()
        header_h = 4
        footer_h = 2
        vis = max(1, h - header_h - footer_h)
        if cursor < scroll:
            scroll = cursor
        if cursor >= scroll + vis:
            scroll = cursor - vis + 1

        if need_draw:
            _tui_draw(stdscr, rows, cursor, scroll, status)
            need_draw = False
        ch = stdscr.getch()
        if ch == -1:
            if poll_picc():
                need_draw = True
            continue
        need_draw = True
        if ch in (ord("q"), 27):
            break
        if ch in (curses.KEY_UP, ord("k")):
            cursor = max(0, cursor - 1)
        elif ch in (curses.KEY_DOWN, ord("j")):
            cursor = min(max(0, len(rows) - 1), cursor + 1)
        elif ch in (curses.KEY_PPAGE,):
            cursor = max(0, cursor - vis)
        elif ch in (curses.KEY_NPAGE,):
            cursor = min(max(0, len(rows) - 1), cursor + vis)
        elif ch in (ord("r"), curses.KEY_F5):
            refresh_rows()
        elif ch in (ord("?"), ord("h")):
            set_poll(False)
            _tui_help(stdscr)
            set_poll(True)
        elif ch in (10, 13, curses.KEY_ENTER):
            if not rows:
                continue
            label, value, hx, cmd, edit = rows[cursor]
            if not edit:
                status = "%s is read-only" % label
                continue
            notes = []
            set_poll(False)
            value_to_set = _tui_edit(stdscr, edit, value)
            set_poll(True)
            if value_to_set is None:
                status = "cancelled"
                continue
            status = "Writing %s…" % label
            _tui_draw(stdscr, rows, cursor, scroll, status)
            stdscr.refresh()
            try:
                notes = _tui_apply(edit, value_to_set, notes.append)
                refresh_rows()
                if notes:
                    status = "  ".join(notes)
            except Exception as e:
                status = "write failed: %s" % e


def _tui_draw(stdscr, rows, cursor, scroll, status):
    """Paint the status table. Dim rows have edit_key None (read-only)."""
    import curses
    stdscr.erase()
    h, w = stdscr.getmaxyx()
    _tui_clip(stdscr, 0, 0, " ACR1552U configuration ",
              curses.A_BOLD | curses.color_pair(1))
    fw = rows[0][1] if rows else "?"
    sn = rows[1][1] if len(rows) > 1 else "?"
    _tui_clip(stdscr, 1, 0, " %s   %s" % (fw, sn), curses.color_pair(3))
    hdr = " %-16s  %-36s  %-8s  %s" % ("Setting", "Value", "Hex", "Command")
    _tui_clip(stdscr, 2, 0, hdr, curses.A_UNDERLINE)
    vis = max(1, h - 6)
    for i, row in enumerate(rows[scroll: scroll + vis]):
        y = 3 + i
        idx = scroll + i
        label, value, hx, cmd, edit = row
        line = " %-16s  %-36s  %-8s  %s" % (
            label[:16], str(value)[:36], str(hx)[:8], cmd)
        attr = 0
        if idx == cursor:
            attr = curses.A_REVERSE
        elif not edit:
            attr = curses.A_DIM
        _tui_clip(stdscr, y, 0, line, attr)
    _tui_clip(stdscr, h - 2, 0, " " + status, curses.color_pair(2))
    stdscr.refresh()


def main():
    """CLI: optional writes, then a status dump. --tui replaces that path."""
    args = parse()
    if args.tui:
        run_tui()
        return
    need_replug = apply(args)
    # Dump after writes so the table is the reader's NV/runtime state, not
    # the requested args. HID-only is delayed until after this dump.
    report()
    if need_replug:
        print("Polling/ATR, PICC type and/or UI written to NV -- unplug and "
              "replug the reader for them to take effect.")
    if args.power is not None:
        print("RF Power written; the reader self-resets once (§6.1.11).")
    if args.suspend:
        hid_mode = args.interface in ("hid", "both")
        if args.interface is None:
            cur = get_interface()
            hid_mode = cur in (0x00, 0x02)
        if hid_mode:
            print("warning: Selective Suspend cannot be enabled in keyboard "
                  "emulation mode (§6.1.13).", file=sys.stderr)
    if args.usb_sn is not None:
        print("S/N in USB Descriptor written -- re-enumerate (unplug/replug) "
              "for the descriptor change to appear.")
    # After the dump so the PICC interface is still present for the Gets.
    if args.interface == "hid":
        set_interface(IFACE_BYTE["hid"])
        print("Host interface is now HID-only; this PC/SC PICC interface will "
              "disappear until it is set back to ccid or both.")
    elif args.watch:
        watch_picc()


if __name__ == "__main__":
    main()
