#!/usr/bin/env python3
# summary: Read or change accessibility settings.
"""starchaser accessibility: shared accessibility settings, applied to the running desktop.

Usage: starchaser accessibility get
       starchaser accessibility set KEY VALUE
       starchaser accessibility start    turn on speech and 150 percent text
       starchaser accessibility toggle   Control Alt A: speech and large text on, or off again when speech is on
       starchaser accessibility apply    restore saved settings at sign-in
       starchaser accessibility refresh-audio  follow the selected sound output while mono audio is on
       starchaser accessibility restore-after-lock  restore accessibility temporarily enabled while locked
       starchaser accessibility login-speech    keep login-screen speech and large text on for this account
       starchaser accessibility say TEXT  say TEXT without a screen reader, then let speech go when none is on
       starchaser accessibility password-keyboard  borrow a keyboard over stdin until the prompt closes
       starchaser accessibility password-keyboard show|restore  show a keyboard or restore its saved setting

Keys: text_scale (1, 1.25, 1.5, 2), high_contrast, screen_reader,
      reduced_motion, sticky_keys, large_pointer, slow_keys, bounce_keys,
      flash_alerts, mono_audio, on_screen_keyboard, mouse_keys (on or off).
      color_filter (off, grayscale, red_green, blue_yellow, invert).
"""
import copy
import fcntl
import json
import os
import re
import shutil
import subprocess
import sys
import signal
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import starchaser_accessibility as prefs
import starchaser_accessibility_effects as effects


def run(*args, env=None):
    result = subprocess.run(args, capture_output=True, text=True, timeout=45, env=env)
    if result.returncode:
        raise RuntimeError(result.stderr.strip() or result.stdout.strip() or f'{args[0]} couldn\'t finish.')
    return result.stdout


def helper(name, *args):
    env = dict(os.environ, STARCHASER_ACCESSIBILITY_APPLY='1') if (name, *args[:1]) == ('starchaser', 'theme') else None
    return run(str(Path(__file__).resolve().with_name(name)), *args, env=env)


class BadValue(ValueError):
    """A value the person typed that the setting doesn't take: exit 2 like other bad input, not a failure."""


def switches(value):
    if value not in ('on', 'off'):
        raise BadValue('Choose on or off.')
    return value == 'on'


def input_settings():
    return json.loads(helper('starchaser', 'input', 'get'))['settings']


def status(data):
    inp = input_settings()
    return dict(data, reduced_motion=inp['animation_speed'] == 'off',
                sticky_keys=inp['sticky_keys'], large_pointer=inp['cursor']['size'] >= 48)


def speech(on):
    run('gsettings', 'set', 'org.gnome.desktop.a11y.applications', 'screen-reader-enabled', str(on).lower())
    run('gdbus', 'call', '--session', '--dest', 'org.a11y.Bus', '--object-path', '/org/a11y/bus',
        '--method', 'org.freedesktop.DBus.Properties.Set', 'org.a11y.Status', 'IsEnabled', '<true>')
    if on:
        # the last session's screen reader can still be exiting at sign-in (its orca lost that session's display):
        # wait for it to end and clear it, or its name blocks a new one and its orca passes for a running one below
        unit_state = run('systemctl', '--user', 'show', '--property=ActiveState', '--value', 'starchaser-screen-reader.service').strip()
        if unit_state in ('deactivating', 'failed'):
            # A reader from before the short stop timeout below can still be waiting out systemd's default.
            # It has already been told to stop; finish that stop before waiting for the unit to be collected.
            if unit_state == 'deactivating':
                subprocess.run(['systemctl', '--user', 'kill', '--signal=SIGKILL', 'starchaser-screen-reader.service'],
                               capture_output=True)
            run('systemctl', '--user', 'stop', 'starchaser-screen-reader.service')
            # best-effort: a unit already collected has nothing to clear
            subprocess.run(['systemctl', '--user', 'reset-failed', 'starchaser-screen-reader.service'], capture_output=True)
        # a screen reader already talking is left alone: "orca --replace" ends it, and the new one starts silent,
        # so the change the person just made is never spoken
        if not speaking():
            environment = [f'--setenv={key}={os.environ[key]}' for key in
                           ('WAYLAND_DISPLAY', 'DISPLAY', 'XDG_RUNTIME_DIR', 'DBUS_SESSION_BUS_ADDRESS') if key in os.environ]
            # Orca's stop ends in SIGKILL (it doesn't leave on SIGTERM); say so here, so turning the screen
            # reader off doesn't journal "Failed with result 'signal'" for a stop that was asked for
            run('systemd-run', '--user', '--unit=starchaser-screen-reader', '--collect', '--service-type=exec',
                '-p', 'SuccessExitStatus=SIGKILL', '-p', 'TimeoutStopSec=2s', *environment, 'orca', '--replace')
            run('systemctl', '--user', 'is-active', 'starchaser-screen-reader.service')
    else:
        # Speak independently of Orca before stopping it; a second shortcut press must not leave unexplained silence.
        try:
            subprocess.run(['spd-say', '-w', '--', 'Screen reader off. Press Control Alt A to turn it on.'],
                           capture_output=True, timeout=6)
        except (OSError, subprocess.SubprocessError):
            pass  # missing or unresponsive speech must not prevent the requested stop
        state = run('systemctl', '--user', 'show', '--property=LoadState', '--value', 'starchaser-screen-reader.service').strip()
        if state != 'not-found':
            run('systemctl', '--user', 'stop', 'starchaser-screen-reader.service')
        # one started outside the unit (left running above instead of replaced) stops too; best-effort: none is fine
        subprocess.run(['pkill', '-x', '-u', str(os.getuid()), 'orca'], capture_output=True)
        release_speech()


SPEECH_UNIT = 'speech-dispatcher.service'
SAY_SECONDS = 10   # the longest thing said here takes about 5 seconds


def say(text):
    """Say TEXT with speech-dispatcher (no screen reader needed), wait until it has been said, then let
    speech-dispatcher go again unless a screen reader uses it."""
    try:
        subprocess.run(['spd-say', '-w', '--', text], capture_output=True, timeout=SAY_SECONDS)
    except (OSError, subprocess.SubprocessError):
        pass  # missing or unresponsive speech: still release it below
    prefs.FILE.parent.mkdir(parents=True, exist_ok=True)
    with prefs.FILE.with_suffix('.lock').open('a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)   # Control Alt A starting the screen reader right now finishes first
        if not prefs.read()['screen_reader']:
            release_speech()


def release_speech():
    """Stop speech-dispatcher when no screen reader is running; its socket starts it again on the next request
    (the screen reader's own, too). Without a sound card a short pause leaves it waiting for its sound to be played,
    asking every 10 ms for the rest of the session (1.7 s of processor a minute with the sound server, RC gate
    1.0.30), and then it ignores a stop: it is ended outright after 2 seconds."""
    if speaking():
        return
    state = subprocess.run(['systemctl', '--user', 'is-active', SPEECH_UNIT], capture_output=True, text=True)
    if state.stdout.strip() not in ('active', 'activating', 'deactivating', 'reloading'):
        return
    try:
        subprocess.run(['systemctl', '--user', 'stop', SPEECH_UNIT], capture_output=True, timeout=2)
    except subprocess.TimeoutExpired:
        subprocess.run(['systemctl', '--user', 'kill', '--signal=SIGKILL', SPEECH_UNIT], capture_output=True)
    # best-effort: a stop ended outright leaves the unit failed, which only clutters the journal's unit list
    subprocess.run(['systemctl', '--user', 'reset-failed', SPEECH_UNIT], capture_output=True)


def speaking():
    """A screen reader is running for this person: its unit, or an orca started some other way."""
    active = subprocess.run(['systemctl', '--user', 'is-active', '--quiet', 'starchaser-screen-reader.service'])
    running = subprocess.run(['pgrep', '-x', '-u', str(os.getuid()), 'orca'], capture_output=True)
    return not (active.returncode and running.returncode)


def native_settings(data):
    inp = input_settings()
    interface = 'org.gnome.desktop.interface'
    a11y = 'org.gnome.desktop.a11y.interface'
    reduced = inp['animation_speed'] == 'off'
    # high-contrast is starchaser theme's (its GTK step, which runs first): on only in light mode
    for schema, key, value in ((a11y, 'reduced-motion', 'reduce' if reduced else 'no-preference'),
                               (interface, 'enable-animations', not reduced),
                               (interface, 'cursor-size', inp['cursor']['size'])):
        run('gsettings', 'set', schema, key, str(value).lower())
    files_layout(data)


BROWSER_CLASSES = frozenset(("chromium", "brave-browser", "brave-origin", "google-chrome", "brave"))
WINDOW_ADDRESS = re.compile(r"0x[0-9a-fA-F]+")


def shortcut_notice(data):
    """Confirm a successful shortcut change for people who do not use speech."""
    speech_on = data['screen_reader']
    large = data['text_scale'] >= 1.5
    message = ('Large text and the screen reader are on.' if speech_on and large else
               'The screen reader is on.' if speech_on else
               'The screen reader is off. Large text stays on.' if large else
               'Large text and the screen reader are off.')
    # Only the shortcut's own enlargement is undone. A size chosen in Settings stays.
    restores_text = data['text_scale'] == 1.5 and data.get('shortcut_text_scale', 1.5) < 1.5
    if speech_on:
        message += (' Ctrl+Alt+A turns them off.' if restores_text else
                    ' Ctrl+Alt+A turns the screen reader off.')
    else:
        message += (' Ctrl+Alt+A turns the screen reader on.' if large else
                    ' Ctrl+Alt+A turns them on.')
    try:
        run(*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then exec "$0" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'],
            str(Path(__file__).resolve().with_name('starchaser-notify')), '-a', 'Starchaser', '-t', '10000', 'Accessibility', message)
    except (OSError, RuntimeError, subprocess.SubprocessError):
        pass  # Notification availability does not undo a completed accessibility change.


def browser_resize_notice():
    """A browser's minimum toolbar width can outgrow a tile when the text grows."""
    try:
        result = subprocess.run(["hyprctl", "clients", "-j"], capture_output=True, text=True, timeout=3)
        windows = json.loads(result.stdout)
        for window in windows:
            address = window.get("address", "")
            if (window.get("class", "").lower() not in BROWSER_CLASSES or window.get("fullscreen", 0) == 2
                    or not WINDOW_ADDRESS.fullmatch(address) or type(window.get("pid")) is not int):
                continue
            subprocess.Popen([str(Path(__file__).resolve()), "browser-fit-notice", address, str(window["pid"])],
                             stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                             start_new_session=True)
    except (OSError, ValueError, subprocess.SubprocessError):
        pass


def redraw_browser_window(address, pid):
    """Make the compositor hand a browser window its tile again, so it is drawn at the tile's full size.

    A browser keeps drawing at the size it had when the text size changed: after large text went off it stayed at
    about two-thirds of its tile (Fable pre-final P2-10). A window that is set to maximized and put back is told its
    size twice, and the second time is the tile's own, so the page redraws to fill it. It stays a tiled window, keeps
    its place, tabs and unfinished work, and the pointer is never touched."""
    if not WINDOW_ADDRESS.fullmatch(address) or type(pid) is not int or pid <= 0:
        raise BadValue("That browser window can't be resized here.")
    result = subprocess.run(["hyprctl", "clients", "-j"], capture_output=True, text=True, timeout=3)
    window = next((w for w in json.loads(result.stdout) if w.get("address") == address and w.get("pid") == pid
                   and w.get("class", "").lower() in BROWSER_CLASSES), None)
    # a window that is already full screen or maximized is drawn at its full size
    if not window or window.get("fullscreen", 0) != 0 or window.get("floating"):
        return False
    target = 'window="address:' + address + '"'
    run("hyprctl", "eval", 'hl.dispatch(hl.dsp.window.fullscreen({mode="maximized", action="set", ' + target + '}))')
    time.sleep(0.4)     # long enough for the browser to draw once at the larger size
    run("hyprctl", "eval", 'hl.dispatch(hl.dsp.window.fullscreen({mode="maximized", action="unset", ' + target + '}))')
    return True


def fit_browser_window(address, pid):
    if not WINDOW_ADDRESS.fullmatch(address) or type(pid) is not int or pid <= 0:
        raise BadValue("That browser window can't be resized here.")
    result = subprocess.run(["hyprctl", "clients", "-j"], capture_output=True, text=True, timeout=3)
    # A closed window's address can be reused. Verify both the process and browser class again.
    window = next((w for w in json.loads(result.stdout) if w.get("address") == address and w.get("pid") == pid
                   and w.get("class", "").lower() in BROWSER_CLASSES), None)
    if not window or window.get("fullscreen", 0) == 2:
        return False
    if window.get("fullscreen", 0) == 1:
        run("hyprctl", "eval", 'hl.dispatch(hl.dsp.window.fullscreen({mode="maximized", action="unset", window="address:' + address + '"}))')
    run("hyprctl", "eval", 'hl.dispatch(hl.dsp.window.fullscreen({mode="maximized", action="set", window="address:' + address + '"}))')
    return True


def offer_browser_fit(address, pid):
    if not WINDOW_ADDRESS.fullmatch(address) or type(pid) is not int or pid <= 0:
        raise BadValue("That browser window can't be resized here.")
    # first the fix itself, then the card as the fallback for a browser that still looks wrong. The pause lets the
    # browser take in the new text size before it is handed its tile again.
    time.sleep(1.5)
    try:
        if redraw_browser_window(address, pid):
            return      # the browser fills its tile again: no card needed
    except (OSError, ValueError, RuntimeError, subprocess.SubprocessError):
        pass    # the card below still offers the full-size button
    result = subprocess.run(["/bin/sh", "-c",
        'token="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/starchaser-notifications/token"; '
        'if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi',
        "starchaser", "notify", "-a", "Starchaser", "-i", "web-browser", "-t", "60000",
        "-h", "string:x-canonical-private-synchronous:browser-text-size-" + address,
        "--action=fit=Make browser full size", "Fit your browser to the new text size",
        "Text size changed. If the browser looks cut off or too small, make this window full size. Your tabs and unfinished work stay open."],
        capture_output=True, text=True, timeout=65)
    if result.returncode == 0 and result.stdout.strip() == "fit":
        fit_browser_window(address, pid)



def files_layout(data):
    """Large text needs rows that grow with the font and enough room for Places. Restore only our own choices."""
    scale = data['text_scale']
    saved = data.get('files_layout')
    if (scale < 1.5 and not saved) or not shutil.which('xfconf-query'):
        return
    keys = {'/last-view': 'string', '/last-separator-position': 'int'}

    def read(key):
        result = subprocess.run(['xfconf-query', '-c', 'thunar', '-p', key], capture_output=True, text=True, timeout=10)
        if result.returncode == 0:
            return result.stdout.strip()
        if result.returncode == 1 and 'does not exist' in result.stderr:
            return None
        raise RuntimeError("Files' layout couldn't be read. Try changing the text size again.")

    if not saved:
        saved = {'before': {key: read(key) for key in keys}, 'applied': {}, 'scale': None}
        data['files_layout'] = saved
    if scale >= 1.5 and saved['scale'] == scale:
        return  # another accessibility change leaves any view the person chose afterward alone
    if scale >= 1.5:
        width = max(int(saved['before']['/last-separator-position'] or 0), round(220 * scale))
        desired = {'/last-view': 'ThunarDetailsView', '/last-separator-position': str(width)}
    else:
        desired = {key: value for key, value in saved['before'].items() if read(key) == saved['applied'].get(key)}
    for key, value in desired.items():
        if scale >= 1.5:
            saved['applied'][key] = value
        if value is None:
            run('xfconf-query', '-c', 'thunar', '-p', key, '--reset')
        else:
            run('xfconf-query', '-c', 'thunar', '-p', key, '--create', '--type', keys[key], '--set', value)
    if scale < 1.5:
        data.pop('files_layout', None)
    else:
        saved['scale'] = scale


def session_locked():
    try:
        result = subprocess.run(['busctl', '--system', 'get-property', 'org.freedesktop.login1',
            '/org/freedesktop/login1/session/auto', 'org.freedesktop.login1.Session', 'LockedHint'],
            capture_output=True, text=True, timeout=3)
        return result.returncode == 0 and result.stdout.strip() == 'b true'
    except (OSError, subprocess.SubprocessError):
        return False


LOCK_KEYS = ('screen_reader', 'text_scale', 'shortcut_text_scale')


def toggle(data):
    """Control Alt A everywhere: speech on with at least 150 percent text, or, when speech is on, speech off and the
    text size from before the shortcut enlarged it. A size picked in Settings stays: only the shortcut's own
    enlargement is undone, and a person already at 200 percent is never shrunk. Speech saved as on with no screen
    reader running (it stopped, or never started at sign-in) is started, not turned off: the key gets the voice back."""
    if data['screen_reader'] and speaking():
        change(data, 'screen_reader', 'off')
        before = data.pop('shortcut_text_scale', None)
        if before is not None and data['text_scale'] == 1.5:
            change(data, 'text_scale', str(before))
    elif not data['screen_reader']:
        data.pop('shortcut_text_scale', None)
        if data['text_scale'] < 1.5:
            data['shortcut_text_scale'] = data['text_scale']
            change(data, 'text_scale', '1.5')
        change(data, 'screen_reader', 'on')


KEYS = ('text_scale', 'high_contrast', 'screen_reader', 'reduced_motion', 'sticky_keys', 'large_pointer',
        'color_filter', 'slow_keys', 'bounce_keys', 'flash_alerts', 'mono_audio', 'on_screen_keyboard', 'mouse_keys')


def change(data, key, value):
    if key == 'color_filter':
        if value not in effects.FILTERS:
            raise BadValue('Choose off, grayscale, red_green, blue_yellow, or invert.')
        data[key] = value
    elif key == 'text_scale':
        try:
            scale = float(value)
        except ValueError:
            raise BadValue('Text scale must be 1, 1.25, 1.5, or 2.') from None
        if scale not in (1, 1.25, 1.5, 2):
            raise BadValue('Text scale must be 1, 1.25, 1.5, or 2.')
        data[key] = scale
    elif key in ('high_contrast', 'screen_reader', 'slow_keys', 'bounce_keys', 'flash_alerts', 'mono_audio', 'on_screen_keyboard', 'mouse_keys'):
        data[key] = switches(value)
    elif key in ('reduced_motion', 'sticky_keys', 'large_pointer'):
        on = switches(value)
        inp = input_settings()
        if key == 'reduced_motion':
            if on and inp['animation_speed'] != 'off':
                data['previous_motion'] = inp['animation_speed']
            target, val = 'animation_speed', 'off' if on else data.get('previous_motion', 'normal')
        elif key == 'large_pointer':
            if on and inp['cursor']['size'] < 48:
                data['previous_pointer'] = inp['cursor']['size']
            target, val = 'cursor.size', str(48 if on else data.get('previous_pointer', 24))
        else:
            target, val = 'sticky_keys', value
        helper('starchaser', 'input', 'set', target, val)
    else:
        raise ValueError(f'Unknown accessibility setting {key!r}.')


def apply_effects(data, previous, args):
    applying = args == ['apply']
    for key in ('color_filter', 'mono_audio', 'on_screen_keyboard'):
        default = 'off' if key == 'color_filter' else False
        # An explicit keyboard request must restore its live state even when the saved setting
        # matches: the password prompt needs to show a hidden keyboard or restart one that exited.
        keyboard_requested = key == 'on_screen_keyboard' and args[:2] == ['set', key]
        if (data.get(key, default) == previous.get(key, default)
                and not (applying and data.get(key, default) != default) and not keyboard_requested):
            continue
        if key == 'color_filter':
            effects.color_filter(data, run, prefs.CONFIG)
        elif key == 'mono_audio':
            effects.mono_audio(data, run)
        else:
            effects.on_screen_keyboard(data.get(key, False), run)
    timing = ('slow_keys', 'bounce_keys', 'mouse_keys')
    if any(data.get(k, False) != previous.get(k, False) for k in timing) or (applying and any(data.get(k, False) for k in timing)):
        run('pkexec', '/usr/local/lib/starchaser/starchaser-accessibility-input', 'set',
            *('on' if data.get(k, False) else 'off' for k in timing))


def password_keyboard():
    """Show a keyboard while the prompt holds its pipe open, without saving a preference."""
    def end_prompt(_signum, _frame):
        raise SystemExit(0)
    # Snapshot the live state as well as the preference: another keyboard user
    # may already have enabled it without changing Starchaser's saved setting.
    saved = prefs.read().get('on_screen_keyboard', False)
    live = run('gsettings', 'get', 'org.gnome.desktop.a11y.applications', 'screen-keyboard-enabled').strip() == 'true'
    previous = signal.signal(signal.SIGTERM, end_prompt)
    try:
        effects.on_screen_keyboard(True, run)
        for request in sys.stdin:
            if request.strip() == "show":
                effects.on_screen_keyboard(True, run)
            elif request.strip() == "restore":
                current = prefs.read().get('on_screen_keyboard', False)
                effects.on_screen_keyboard(current if current != saved else saved or live, run)
    finally:
        # Respect a preference changed independently while the password prompt was open.
        current = prefs.read().get('on_screen_keyboard', False)
        restore = current if current != saved else saved or live
        try:
            effects.on_screen_keyboard(restore, run)
        finally:
            signal.signal(signal.SIGTERM, previous)
    return 0


def main(args):
    if len(args) == 2 and args[0] == 'password-keyboard' and args[1] in ('show', 'restore'):
        # Explicit callers can borrow the keyboard without changing the saved preference.
        effects.on_screen_keyboard(args[1] == 'show' or prefs.read().get('on_screen_keyboard', False), run)
        return 0
    if args == ['password-keyboard']:
        return password_keyboard()
    if len(args) == 2 and args[0] == 'say':
        say(args[1])
        return 0
    if len(args) == 3 and args[0] == 'browser-fit-notice':
        try:
            pid = int(args[2])
        except ValueError:
            raise BadValue('Choose an open browser window.') from None
        offer_browser_fit(args[1], pid)
        return 0
    if args in (['--help'], ['-h'], ['help']) or any(a in ('-h', '--help') for a in args[1:]):
        print(__doc__)
        return 0
    if not (args in (['get'], ['start'], ['toggle'], ['apply'], ['login-speech'], ['restore-after-lock'], ['refresh-audio']) or len(args) == 3 and args[0] == 'set' and args[1] in KEYS):
        if not args:
            message = 'Choose a command: get, set, start, toggle, or apply.'
        elif args[0] == 'set' and len(args) == 3:
            message = f'unknown setting {args[1]!r}. Choose from {", ".join(KEYS)}.'
        elif args[0] == 'set':
            message = 'set needs a setting and a value. Example: starchaser accessibility set text_scale 1.5'
        elif args[0] in ('get', 'start', 'toggle', 'apply', 'login-speech', 'restore-after-lock', 'refresh-audio'):
            message = f'{args[0]} takes nothing after it (got {args[1]!r}).'
        else:
            message = f'Unknown {"option" if args[0].startswith("-") else "command"} {args[0]!r}.'
        print(f"starchaser accessibility: {message}\nRun 'starchaser accessibility --help' for more help.", file=sys.stderr)
        return 2
    prefs.FILE.parent.mkdir(parents=True, exist_ok=True)
    with prefs.FILE.with_suffix('.lock').open('a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        data = prefs.read()
        if args == ['get']:
            print(json.dumps(status(data)))
            return 0
        if args == ['refresh-audio']:
            effects.mono_audio(data, run)
            print(json.dumps({'mono_audio': data.get('mono_audio', False)}))
            return 0
        if args == ['login-speech']:
            # The session calls this before its display starts. Save only; normal sign-in apply starts Orca and sizes
            # the text. Control Alt A at the login screen turned on speech and large text, so both carry over, the
            # size remembered as the shortcut's own (QA 2026-11-04); speech already on keeps the size it has.
            if not data['screen_reader'] and data['text_scale'] < 1.5:
                data['shortcut_text_scale'] = data['text_scale']
                data['text_scale'] = 1.5
            data['screen_reader'] = True
            prefs.write(data)
            return 0
        previous = copy.deepcopy(data)
        if args in (['restore-after-lock'], ['apply']):
            snapshot = data.pop('lock_shortcut_previous', None)
            if not isinstance(snapshot, dict) and args == ['restore-after-lock']:
                return 0
            snapshot = snapshot if isinstance(snapshot, dict) else {k:data[k] for k in LOCK_KEYS if k in data}
            for key in LOCK_KEYS:
                if key in snapshot: data[key] = snapshot[key]
                else: data.pop(key, None)
        previous_input = input_settings()
        if args == ['start']:
            # at least 150 percent: a larger size the person already picked stays (200 dropped to 150, QA 2026-11-03)
            if data['text_scale'] < 1.5:
                # remembered like Control Alt A's: turning speech off with the shortcut puts this size back (QA 2026-11-03)
                data['shortcut_text_scale'] = data['text_scale']
                change(data, 'text_scale', '1.5')
            change(data, 'screen_reader', 'on')
        elif args == ['toggle']:
            if not data['screen_reader'] and session_locked() and 'lock_shortcut_previous' not in data:
                data['lock_shortcut_previous'] = {k: copy.deepcopy(data[k]) for k in LOCK_KEYS if k in data}
            toggle(data)
        elif args[0] == 'set':
            change(data, args[1], args[2])
        # The theme keeps the unscaled Qt fonts so repeated changes never compound.
        if data['text_scale'] != 1 and 'qt_fonts' not in data:
            import configparser
            fonts = {}
            for tool in ('qt6ct', 'qt5ct'):
                conf = configparser.ConfigParser(interpolation=None)
                conf.read(prefs.CONFIG / tool / (tool + '.conf'))
                fonts[tool] = dict(conf['Fonts']) if conf.has_section('Fonts') else {}
            data['qt_fonts'] = fonts
        prefs.write(data)
        try:
            # only the screen reader's own switch (and start / apply at sign-in) starts or stops speech; a text size or
            # contrast change leaves the running screen reader alone, so it can say what changed
            if (data['screen_reader'] or previous['screen_reader']) and (args[0] != 'set' or args[1] == 'screen_reader'):
                speech(data['screen_reader'])
            try:
                helper('starchaser', 'theme', 'reapply')
            except (OSError, RuntimeError, subprocess.SubprocessError):
                # the tool's own one line: the helper's answer is its own business, and a wall of its text
                # (a traceback among it) is never what the person reads here
                raise RuntimeError("starchaser accessibility: the appearance couldn't be fully applied "
                                   "(the theme step failed); your settings were put back.") from None
            apply_effects(data, previous, args)
            native_settings(data)
            prefs.write(data)
        except (OSError, RuntimeError, subprocess.SubprocessError):
            if 'files_layout' in data:
                previous['files_layout'] = copy.deepcopy(data['files_layout'])
                previous['files_layout']['scale'] = None
            prefs.write(previous)
            # Restore the previous live state if only part of a change could be applied.
            try:
                if args[0] == 'set' and args[1] in ('reduced_motion', 'large_pointer', 'sticky_keys'):
                    key = args[1]
                    target, value = {'reduced_motion': ('animation_speed', previous_input['animation_speed']),
                                     'large_pointer': ('cursor.size', str(previous_input['cursor']['size'])),
                                     'sticky_keys': ('sticky_keys', 'on' if previous_input['sticky_keys'] else 'off')}[key]
                    helper('starchaser', 'input', 'set', target, value)
                if data['screen_reader'] != previous['screen_reader']:
                    speech(previous['screen_reader'])
                helper('starchaser', 'theme', 'reapply')
                apply_effects(previous, data, args)
                native_settings(previous)
                prefs.write(previous)
            except (OSError, RuntimeError, subprocess.SubprocessError):
                pass  # The original failure is reported; the saved choices remain the previous ones.
            raise
        if data['text_scale'] == 1 and 'qt_fonts' in data:
            del data['qt_fonts']  # Stop owning native font choices after restoring them.
            prefs.write(data)
        if data['text_scale'] != previous['text_scale']:
            browser_resize_notice()
        if args == ['toggle']:
            shortcut_notice(data)
        if args == ['restore-after-lock']:
            message = 'Restored your previous screen reader and text size settings after unlocking.'
            try:
                run(*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then exec "$0" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], str(Path(__file__).resolve().with_name('starchaser-notify')), '-a', 'Starchaser', 'Accessibility restored', message)
                # said in the background: the unlock doesn't wait, and speech is let go of afterward
                subprocess.Popen([str(Path(__file__).resolve()), 'say', message], start_new_session=True,
                                 stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            except (OSError, RuntimeError, subprocess.SubprocessError):
                pass
        print(json.dumps(status(data)))
    return 0


if __name__ == '__main__':
    try:
        sys.exit(main(sys.argv[1:]))
    except BadValue as error:
        print(f"starchaser accessibility: {error}\nRun 'starchaser accessibility --help' for more help.", file=sys.stderr)
        sys.exit(2)
    except OSError as error:               # a settings folder it may not use: say so, not a raw errno line
        print(f"starchaser accessibility: couldn't save your settings ({error.strerror}). "
              "Check that you can write to ~/.config.", file=sys.stderr)
        sys.exit(1)
    except (ValueError, KeyError, RuntimeError, subprocess.SubprocessError) as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
