#!/usr/bin/env python3
# summary: Find printers, manage print jobs, and change printer settings.
"""starchaser printers: the printers Settings > Printers shows, and the changes it makes.

  starchaser printers status            JSON: your printers and their status, printers found on networks you
                                        trust, and your default printer
  starchaser printers printers          JSON: the same without the network search, which can take a while
  starchaser printers found             JSON: only the printers found on networks you trust
  starchaser printers add ADDRESS [NAME]
                                        add a printer by its address: ipp://..., ipps://..., a name such as
                                        office-printer.local, or an IP address such as 192.168.1.20 (asks for your
                                        password)
  starchaser printers add-legacy ADDRESS NAME PPD
                                        add an older USB or network printer with its manufacturer's PPD file
  starchaser printers local             JSON: connected USB printers and their addresses
  starchaser printers resume NAME       resume a paused printer (asks for your password)
  starchaser printers cancel JOB        cancel one waiting print job, such as Office-42
  starchaser printers remove NAME       remove a printer (asks for your password)
  starchaser printers default NAME      make NAME your default printer (only for your account; no password)
  starchaser printers test NAME         print a test page
  starchaser printers print-text        print the text on standard input on your default printer (the recovery steps);
                                        with no printer set up, or printing off, it shows the same notice as the
                                        print dialog and fails
  starchaser printers turn-on           switch printing on when it is off: it then starts when something prints
                                        (asks for your password)
  starchaser printers watch-print [PID]
                                        while the Document Viewer (process PID) runs, or with no PID for the whole
                                        session: when its or the Text editor's Print dialog opens and no printer is set
                                        up, say so in a notice that opens Settings > Printers (started by the papers
                                        wrapper and at session start; prints nothing)

Changes print JSON ({"ok": true, ...} or {"ok": false, "errors": "..."}) and exit 1 when they fail.
Printers are found only on networks you trust (Settings > Firewall). Printing starts only when it is used.
"""
import ipaddress
import json
import os
import re
import shlex
import shutil
import socket
import subprocess
import sys
import time
from pathlib import Path
from urllib.parse import quote, urlsplit

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import safe_streams, usage_error

PROG = "starchaser printers"
COMMANDS = {"status": "status", "printers": "printers", "found": "found", "add": "add ADDRESS [NAME]", "remove": "remove NAME", "default": "default NAME",
            "test": "test NAME", "turn-on": "turn-on", "print-text": "print-text", "watch-print": "watch-print [PID]", "add-legacy": "add-legacy ADDRESS NAME PPD",
            "auto-usb": "auto-usb", "watch-usb": "watch-usb", "drivers": "drivers [WORDS]", "add-driver": "add-driver ADDRESS NAME DRIVER", "defaults": "defaults NAME PAPER SIDES", "details": "details NAME", "local": "local", "resume": "resume NAME", "cancel": "cancel JOB"}
POLICY = Path("/etc/starchaser/policy.json")
ZONEMAP = Path("/run/starchaser/firewall-zones.json")
TEST_PAGE = Path("/usr/share/cups/data/testprint")
AREA = "/usr/local/lib/starchaser/starchaser-admin-area"
PK = ("org.opensuse.CupsPkHelper.Mechanism", "/", "org.opensuse.CupsPkHelper.Mechanism")
SERVICE_TYPES = ("_ipps._tcp", "_ipp._tcp")          # the encrypted one first: it wins when a printer offers both
# CUPS queue names: printable, no spaces, slashes, #, ? or quotes; never an option to the commands below
NAME = re.compile(r"[^\x00-\x20\x7f/\\#?'\"-][^\x00-\x20\x7f/\\#?'\"]{0,126}\Z")
HOST = re.compile(r"(?=.{1,253}\Z)[A-Za-z0-9](?:[A-Za-z0-9-]{0,62})(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,62}))*\.?\Z")
# the Document Viewer and Text editor's GTK print dialogs: each can use the executable name instead of the
# document window's app ID (QA 20261107-0832 001, 20261110-0242 001), and the dialog's title
PRINT_APPS, PRINT_TITLE = ("org.gnome.Papers", "papers", "org.xfce.mousepad", "mousepad",
                           "xdg-desktop-portal-gtk", "org.freedesktop.impl.portal.desktop.gtk"), "Print"
NOT_ANSWERING = "The printer did not answer. Check that it is turned on and connected to this network, and that the address is right."

# The guard that keeps discovery to networks you trust (the root helpers' printing.py): the checkout's copy first,
# like starchaser firewall's engine. Importing it needs no root and runs nothing.
printing = None
for _lib in (Path(__file__).resolve().parent.parent / "system/usr/local/lib/starchaser", Path("/usr/local/lib/starchaser")):
    if (_lib / "printing.py").is_file():
        sys.path.insert(0, str(_lib))
        try:
            import printing
        except Exception:                               # an older or broken copy: only this computer's own printers
            printing = None
        break


class Failed(Exception):
    pass


class Canceled(Exception):
    pass


def run(args, timeout=20):
    env = dict(os.environ, LC_ALL="C", LANG="C")        # lpstat's words are parsed below
    try:
        return subprocess.run(args, capture_output=True, text=True, timeout=timeout, env=env)
    except subprocess.TimeoutExpired:
        return subprocess.CompletedProcess(args, 124, "", "timed out")
    except OSError as e:
        return subprocess.CompletedProcess(args, 127, "", str(e))


def jread(path, default):
    try:
        return json.loads(path.read_text())
    except (OSError, ValueError):
        return default


# ---------------------------------------------------------------- reading

def unescape(text):
    """avahi-browse -p writes \\032 for a space and \\. for a dot."""
    return re.sub(r"\\(\d{3}|.)", lambda m: chr(int(m.group(1))) if m.group(1).isdigit() else m.group(1), text)


def printer_list():
    """[{name, info, uri, state, status, alerts}] for the printers added to this computer."""
    listed = run(["lpstat", "-l", "-p"])
    words = (listed.stderr + listed.stdout).lower()
    if listed.returncode and "no destinations" not in words:
        raise Failed("Printing couldn't be checked. Press Check again.")
    uris = {}
    for line in run(["lpstat", "-v"]).stdout.splitlines():
        m = re.match(r"device for (\S+): (\S+)", line)
        if m:
            uris[m.group(1)] = m.group(2)
    out, cur = [], None
    for line in listed.stdout.splitlines():
        m = re.match(r"printer (\S+) (?:is idle|now printing (\S+?)\.|disabled since)", line)
        if m:
            cur = {"name": m.group(1), "info": "", "uri": uris.get(m.group(1), ""), "alerts": [],
                   "state": "printing" if m.group(2) else "paused" if "disabled since" in line else "ready"}
            out.append(cur)
            continue
        if cur is None or not line.startswith("\t"):
            continue
        item = line.strip()
        if item.startswith("Description:"):
            cur["info"] = item.split(":", 1)[1].strip()
        elif item.startswith("Alerts:"):
            cur["alerts"] = [a for a in item.split(":", 1)[1].split() if a != "none"]
    for p in out:
        p["status"] = status_words(p)
        p["usb"] = p["uri"].startswith(("usb:", "ippusb:", "ipp://localhost:", "ipp://127.0.0.1:"))
    return out


ALERTS = (("offline", "Not responding. Check that it is turned on and connected."),
          ("media-jam", "Paper jam"), ("media-empty", "Out of paper"), ("media-needed", "Out of paper"),
          ("door-open", "A door or cover is open"), ("cover-open", "A door or cover is open"),
          ("toner-empty", "Out of toner"), ("marker-supply-empty", "Out of ink or toner"),
          ("toner-low", "Low on toner"), ("marker-supply-low", "Low on ink or toner"))


def status_words(p):
    alerts = [re.sub(r"-(report|warning|error)$", "", a) for a in p["alerts"]]
    for key, words in ALERTS:
        if key in alerts:
            return words
    return {"ready": "Ready", "printing": "Printing"}.get(p["state"], "Paused")


def printer_jobs():
    result = run(["lpstat", "-o"])
    if result.returncode and "no destinations" not in (result.stderr + result.stdout).lower():
        raise Failed("Waiting print jobs couldn't be checked. Press Check again.")
    out = []
    for line in result.stdout.splitlines():
        match = re.match(r"([^\s]+)-(\d+)\s+(\S+)\s+(\d+)\s+(.*)", line)
        if match and NAME.fullmatch(match.group(1)):
            name, number, owner, size, submitted = match.groups()
            out.append({"id": name + "-" + number, "printer": name, "owner": owner, "bytes": int(size), "submitted": submitted})
    return out


def resume(name):
    need_name(name)
    pk("PrinterSetEnabled", "sb", name, "true")
    pk("PrinterSetAcceptJobs", "sbs", name, "true", "")
    return {"ok": True, "name": name}


def cancel_job(job):
    if not re.fullmatch(r"[^\s]+-[0-9]+", job) or job.startswith('-'):
        raise Failed("Choose one waiting print job to cancel.")
    if not any(item["id"] == job for item in printer_jobs()):
        raise Failed("That job has already finished or was canceled. Check again.")
    result = run(["cancel", job])
    if result.returncode:
        pk("JobCancelPurge", "ib", job.rsplit("-", 1)[1], "false")
    return {"ok": True, "job": job}


def local_printers():
    result = run(["lpinfo", "--include-schemes", "usb", "-v"], timeout=10)
    out = []
    for line in result.stdout.splitlines():
        if line.startswith("direct usb://"):
            uri = line.split(None, 1)[1]
            out.append({"uri": uri, "name": uri.removeprefix("usb://").split('?')[0].replace('%20', ' ')})
    return {"ok": result.returncode == 0, "local": out}


def default_printer():
    """Your default printer (your own choice, else this computer's), or ''."""
    m = re.search(r"destination: (\S+)", run(["lpstat", "-d"]).stdout)
    return m.group(1) if m else ""


def listen_interfaces():
    zones = jread(ZONEMAP, {}).get("zones") or {}
    if printing is None:
        return {"lo"}, bool(zones.get("trusted")), False, False
    policy = jread(POLICY, {})
    opened = printing.open_zones(policy)
    # wider: Firewall lets mDNS through on more kinds of network than Trusted (the person's own choice)
    return (set(printing.listen_interfaces(policy, zones)), bool(zones.get("trusted")), opened == "any",
            opened == "any" or opened != {"trusted"})


def found_printers(listen, everywhere, added):
    """[{name, model, address, uri}] printers announcing themselves where discovery is allowed, not yet added."""
    found = {}
    for kind in SERVICE_TYPES:
        r = run(["avahi-browse", "-t", "-r", "-p", "-k", kind], timeout=8)
        for line in r.stdout.splitlines():
            f = line.split(";", 9)
            if len(f) < 10 or f[0] != "=" or (not everywhere and f[1] not in listen):
                continue
            name, domain, host, addr, port = unescape(f[3]), unescape(f[5]), unescape(f[6]).rstrip("."), f[7], f[8]
            if name in found:
                continue
            txt = dict(t.split("=", 1) for t in (unescape(x) for x in re.findall(r'"((?:[^"\\]|\\.)*)"', f[9])) if "=" in t)
            uri = "dnssd://" + quote(f"{name}.{kind}.{domain}", safe="") + "/"
            if txt.get("UUID"):
                uri += "?uuid=" + quote(txt["UUID"], safe="")
            found[name] = {"name": name, "model": txt.get("ty", ""), "address": host or addr, "uri": uri,
                           "hosts": {(h.lower(), port) for h in (host, addr) if h}}
    # one already added: by its found address, or by the host and port it was added with
    taken = set()
    for p in added:
        u = urlsplit(p["uri"])
        taken.add(p["uri"].split("?")[0])
        try:
            if u.hostname:
                taken.add((u.hostname.lower().rstrip("."), str(u.port or 631)))
        except ValueError:
            pass
    out = []
    for p in found.values():
        if p["uri"].split("?")[0] in taken or p["hosts"] & taken:
            continue
        del p["hosts"]
        out.append(p)
    return sorted(out, key=lambda p: p["name"].lower())


def switched_off():
    """Printing isn't running and nothing starts it: CUPS's socket is not turned on (a computer set up before
    printing support came, or someone turned it off). Turn on printing fixes that; updates don't."""
    listed = run(["lpstat", "-r"])
    if "not running" not in (listed.stdout + listed.stderr).lower():
        return False
    return run(["systemctl", "is-enabled", "--quiet", "cups.socket"]).returncode != 0


def status(search=True):
    """search=False leaves out the network search, so Settings shows your printers and the add box without
    waiting for it (QA 2026-11-04: about 20 seconds of only "Checking printers…")."""
    if not shutil.which("lpstat"):
        return {"ok": True, "installed": False, "printers": [], "found": [], "default": "", "trusted": False,
                "wider": False}
    if switched_off():
        return {"ok": True, "installed": True, "off": True, "printers": [], "found": [], "default": "",
                "trusted": False, "wider": False}
    printers = printer_list()
    default = default_printer()
    jobs = printer_jobs()
    for p in printers:
        p["jobs"] = [j for j in jobs if j["printer"] == p["name"]]
        p["default"] = p["name"] == default
    listen, trusted, everywhere, wider = listen_interfaces()
    return {"ok": True, "installed": True, "printers": printers,
            "found": found_printers(listen, everywhere, printers) if search else [],
            "default": default, "trusted": trusted, "wider": wider}


def found():
    if not shutil.which("lpstat") or switched_off():
        return {"ok": True, "found": []}
    listen, _, everywhere, _ = listen_interfaces()
    return {"ok": True, "found": found_printers(listen, everywhere, printer_list())}


# ---------------------------------------------------------------- changing

def check_host(host):
    try:
        ipaddress.ip_address(host)
        return host
    except ValueError:
        pass
    if not HOST.match(host):
        raise Failed("That address doesn't look right. Type the printer's name or IP address, for example 192.168.1.20.")
    return host


def printer_uri(address):
    """The device address CUPS is given for what someone typed (or a found printer's dnssd:// address)."""
    a = address.strip()
    if not a or len(a) > 512 or any(c.isspace() or ord(c) < 32 or c == "\x7f" for c in a):
        raise Failed("Type the printer's address, for example 192.168.1.20 or ipp://192.168.1.20/ipp/print.")
    low = a.lower()
    if low.startswith("dnssd://"):
        if not re.fullmatch(r"dnssd://[A-Za-z0-9%._~-]+/(\?uuid=[A-Za-z0-9%:-]+)?", a):
            raise Failed("That found printer's address can't be used. Press Check again.")
        return a
    if low.startswith("usb://"):
        u = urlsplit(a)
        if not u.netloc or not u.path or u.username or u.password or u.fragment:
            raise Failed("Choose a connected USB printer below.")
        return a
    if low.startswith(("socket://", "lpd://")):
        u = urlsplit(a)
        try:
            port = u.port
        except ValueError:
            raise Failed("The port number in that address isn't right.") from None
        if not u.hostname or u.username or u.password or u.fragment or (port is not None and not 0 < port < 65536):
            raise Failed("Check the printer's network address.")
        check_host(u.hostname)
        return a
    if low.startswith(("ipp://", "ipps://")):
        u = urlsplit(a)
        try:
            port = u.port
        except ValueError:
            raise Failed("The port number in that address isn't right.") from None
        if not u.hostname or u.username or u.password or u.fragment:
            raise Failed("That address doesn't look right. Type the printer's name or IP address, for example 192.168.1.20.")
        host = check_host(u.hostname)
        netloc = (f"[{host}]" if ":" in host else host) + (f":{port}" if port else "")
        path = u.path if u.path not in ("", "/") else "/ipp/print"
        return f"{u.scheme.lower()}://{netloc}{quote(path, safe='/%._~-')}" + (f"?{u.query}" if u.query else "")
    if "://" in a:
        raise Failed("Use ipp:// or ipps:// for driverless printing, or socket://, lpd:// or usb:// with a printer description file.")
    host, port = a, ""
    m = re.fullmatch(r"\[([0-9A-Fa-f:.]+)\](?::(\d{1,5}))?", a) or (a.count(":") == 1 and re.fullmatch(r"([^:]+):(\d{1,5})", a))
    if m:
        host, port = m.group(1), m.group(2) or ""
    if port and not 0 < int(port) < 65536:
        raise Failed("The port number in that address isn't right.")
    host = check_host(host)
    return f"ipp://{f'[{host}]' if ':' in host else host}{':' + port if port else ''}/ipp/print"


def all_names():
    return {line.strip().lower() for line in run(["lpstat", "-e"]).stdout.splitlines() if line.strip()}


def queue_name(wanted, uri):
    """A free CUPS name from the name asked for, else from the address: letters, digits, - and _ only."""
    base = wanted or urlsplit(uri).hostname or "Printer"
    if uri.startswith("dnssd://") and not wanted:
        base = urlsplit(uri).netloc.split(".")[0]
        base = re.sub(r"%[0-9A-Fa-f]{2}", " ", base)
    base = re.sub(r"[^A-Za-z0-9_-]+", "_", base).strip("_-")[:64] or "Printer"
    taken, name, n = all_names(), base, 2
    while name.lower() in taken:
        name, n = f"{base}_{n}", n + 1
    return name


def pk(method, signature, *values, timeout=25):
    """One cups-pk-helper call (it asks for the password through the normal prompt). Its answer is an error
    sentence, empty on success."""
    r = run(["busctl", "--system", f"--timeout={timeout}", "--json=short", "call", *PK, method, signature, *values],
            timeout=timeout + 5)
    if r.returncode:
        words = r.stderr.strip()
        if re.search(r"not ?privileged|not authori[sz]ed|dismiss|cancel", words, re.I):
            raise Canceled()
        if re.search(r"not provided by any|ServiceUnknown|could not activate", words, re.I):
            raise Failed("Printer support isn't fully installed. Install Starchaser updates in Settings > Updates, then try again.")
        raise Failed(NOT_ANSWERING if r.returncode == 124 else "The change couldn't be made. Try again.")
    try:
        err = (json.loads(r.stdout).get("data") or [""])[0]
    except (ValueError, AttributeError):
        err = ""
    if err:
        if re.search(r"not ?privileged|not authori[sz]ed", err, re.I):
            raise Canceled()
        # CUPS's own words for a printer it couldn't reach, such as "server-error-device-error", are never shown
        raise Failed(NOT_ANSWERING if re.search(r"connect|not possible|timed out|unable|ipp connection|device-error"
                                                r"|not-found|service-unavailable", err, re.I)
                     else f"The change couldn't be made: {err}")


def answers(host, port):
    """True when something at host:port takes a connection within a few seconds."""
    try:
        socket.create_connection((host, port), timeout=5).close()
        return True
    except (OSError, ValueError):
        return False


def check_answers(uri):
    """A typed address is tried before the password prompt, so a wrong address or a printer that is off is said
    in seconds instead of after the password and a minute of waiting. A found printer (dnssd://) just answered."""
    u = urlsplit(uri)
    if u.scheme in ("ipp", "ipps", "socket", "lpd") and not answers(u.hostname, u.port or {"socket": 9100, "lpd": 515}.get(u.scheme, 631)):
        raise Failed(f"No printer answered at {u.hostname}. Check that it is turned on and connected to this "
                     "network, and that the address is right.")


def need_name(name):
    if not NAME.match(name):
        raise Failed("That isn't a printer's name.")
    if name.lower() not in all_names():
        raise Failed("That printer isn't on this computer anymore. Press Check again.")
    return name


def add(address, wanted="", ppd="", driver=""):
    if wanted and not NAME.match(wanted):
        raise Failed("A printer's name can't have spaces, slashes, #, ? or quotes.")
    uri = printer_uri(address)
    if ppd:
        file = Path(ppd).expanduser().resolve()
        try:
            with file.open('rb') as description:
                valid = description.read(64).startswith(b'*PPD-Adobe:')
            if not valid or file.stat().st_size > 4 * 1024 * 1024:
                raise OSError()
        except OSError:
            raise Failed("Choose a readable printer description (.ppd) file from the printer's manufacturer.") from None
    elif not driver and urlsplit(uri).scheme not in ('ipp', 'ipps', 'dnssd'):
        raise Failed("This printer needs a printer description (.ppd) file. Choose the file, then add it again.")
    check_answers(uri)
    name = queue_name(wanted, uri)
    info = wanted or (re.sub(r"%[0-9A-Fa-f]{2}", " ", urlsplit(uri).netloc.split(".")[0]) if uri.startswith("dnssd://")
                      else urlsplit(uri).hostname or name)
    # IPP Everywhere: the printer describes itself, so no driver is needed. Adding asks the printer, which can take
    # a while, and the password prompt waits for a person too.
    if ppd:
        pk("PrinterAddWithPpdFile", "sssss", name, uri, str(file), info, "", timeout=300)
    else:
        pk("PrinterAdd", "sssss", name, uri, driver or "everywhere", info, "", timeout=300)
    state = run(["lpstat", "-p", name]).stdout
    if "disabled" in state:
        pk("PrinterSetEnabled", "sb", name, "true")
    if "not accepting" in run(["lpstat", "-a", name]).stdout:
        pk("PrinterSetAcceptJobs", "sbs", name, "true", "")
    # A new printer is shared by default: other computers would see a printer they can't reach (printing listens
    # on this computer only), so it is kept to this computer.
    if "printer-is-shared=true" in run(["lpoptions", "-p", name]).stdout:
        pk("PrinterSetShared", "sb", name, "false")
    made_default = False
    if not default_printer():
        made_default = run(["lpoptions", "-d", name]).returncode == 0
    return {"ok": True, "name": name, "uri": uri, "default": made_default}


def drivers(query=""):
    result = run(["lpinfo", "-m"], timeout=30)
    if result.returncode:
        raise Failed("Printer drivers couldn't be read. Install the waiting system updates, then try again.")
    rows = []
    for line in result.stdout.splitlines():
        driver, _, label_ = line.partition(" ")
        if driver and label_ and all(word in label_.lower() for word in query.lower().split()):
            rows.append({"id": driver, "name": re.sub(r"\s+- CUPS\+.*$", "", label_)})
    return {"ok": True, "drivers": rows[:100]}


def add_driver(address, name, driver):
    if not any(row["id"] == driver for row in drivers()["drivers"]):
        # A targeted query cannot validate an arbitrary driver path. Validate against the complete local list.
        result = run(["lpinfo", "-m"])
        if driver not in {line.split(" ", 1)[0] for line in result.stdout.splitlines()} or result.returncode:
            raise Failed("Choose a driver installed on this computer.")
    return add(address, name, driver=driver)


def set_defaults(name, paper, sides):
    need_name(name)
    if paper not in ("Letter", "Legal", "Executive", "A4", "A5") or sides not in ("one-sided", "two-sided-long-edge", "two-sided-short-edge"):
        raise Failed("Choose a listed paper size and one-sided or two-sided printing.")
    result = run(["lpoptions", "-p", name, "-o", "media=" + paper, "-o", "sides=" + sides])
    if result.returncode:
        raise Failed("The print defaults couldn't be saved.")
    return {"ok": True, "message": "Print defaults saved for your account."}


def paper_name(value):
    value = value.split(',')[0]
    aliases = {'na_letter_8.5x11in': 'Letter', 'na_legal_8.5x14in': 'Legal',
               'na_executive_7.25x10.5in': 'Executive', 'iso_a4_210x297mm': 'A4', 'iso_a5_148x210mm': 'A5'}
    return aliases.get(value.lower(), value)


def details(name):
    need_name(name)
    result = run(["ipptool", "-tv", "ipp://localhost/printers/" + quote(name, safe=""),
                  "/usr/share/cups/ipptool/get-printer-attributes.test"], timeout=10)
    attrs = {}
    for line in result.stdout.splitlines():
        match = re.match(r"\s*(marker-names|marker-levels|media-default|sides-default|sides-supported|media-supported) \([^)]*\) = (.*)", line)
        if match:
            attrs[match.group(1)] = match.group(2).strip()
    levels, supplies = attrs.get("marker-levels", "").split(','), []
    for i, name_ in enumerate(attrs.get("marker-names", "").split(',')):
        if name_ and i < len(levels):
            try:
                level = int(levels[i])
            except ValueError:
                level = -1
            supplies.append({"name": name_, "percent": level if 0 <= level <= 100 else None})
    current = run(["lpoptions", "-p", name])
    try:
        options = dict(word.split('=', 1) for word in shlex.split(current.stdout) if '=' in word) if current.returncode == 0 else {}
    except ValueError:
        options = {}
    legacy_sides = {'DuplexNoTumble': 'two-sided-long-edge', 'DuplexTumble': 'two-sided-short-edge', 'None': 'one-sided'}
    return {"ok": True, "supplies": supplies,
            "paper": paper_name(options.get('media') or options.get('PageSize') or attrs.get('media-default', '')),
            "sides": options.get('sides') or legacy_sides.get(options.get('Duplex')) or attrs.get('sides-default', ''),
            "twoSided": "two-sided" in attrs.get("sides-supported", "")}


def remove(name):
    need_name(name)
    pk("PrinterDelete", "s", name, timeout=120)
    # best-effort: your own options for it (its line in ~/.cups/lpoptions, and the default when it was that)
    run(["lpoptions", "-x", name])
    return {"ok": True, "name": name}


def make_default(name):
    need_name(name)
    # Your own choice, in CUPS's own file for your account (~/.cups/lpoptions); this computer's default is kept
    # for everyone else, and Starchaser keeps no copy of either.
    r = run(["lpoptions", "-d", name])
    if r.returncode:
        raise Failed("The default printer couldn't be changed. Try again.")
    return {"ok": True, "name": name}


def test_page(name):
    need_name(name)
    if not TEST_PAGE.is_file():
        raise Failed("The test page is missing. Install Starchaser updates in Settings > Updates, then try again.")
    # CUPS-PDF sanitizes spaces and can prefer an embedded title. A job label lets us find only this output.
    options = ["-o", "TitlePref=1", "-o", "Label=1"] if name == "Save_as_PDF" else []
    r = run(["lp", "-d", name, "-t", "Test page", *options, str(TEST_PAGE)], timeout=60)
    m = re.search(r"request id is (\S+)", r.stdout)
    if r.returncode or not m:
        raise Failed("The test page couldn't be sent. Check the printer's status above, then try again.")
    if name == "Save_as_PDF":
        save_pdf_test_page(m.group(1))
    return {"ok": True, "name": name, "job": m.group(1)}


def save_pdf_test_page(job):
    match = re.fullmatch(r"Save_as_PDF-(\d+)", job)
    if not match:
        raise Failed("The PDF test page couldn't be checked. Try again.")
    folder = Path.home() / "Documents/PDF"
    source = folder / f"job_{match.group(1)}-Test_page.pdf"
    deadline = time.monotonic() + 60
    while time.monotonic() < deadline:
        pending = run(["lpstat", "-W", "not-completed", "-o", "Save_as_PDF"])
        # Ghostscript creates the file before it finishes writing; wait until the job leaves the active queue.
        if pending.returncode == 0 and not re.search(r"^" + re.escape(job) + r"\s", pending.stdout, re.M) and source.exists():
            try:
                index = 1
                while True:
                    target = folder / ("Test page.pdf" if index == 1 else f"Test page ({index}).pdf")
                    try:
                        os.link(source, target)
                        break
                    except FileExistsError:
                        index += 1
                source.unlink()
            except OSError:
                raise Failed("The test page couldn't be named. Check Documents > PDF, then try again.") from None
            return
        time.sleep(0.25)
    raise Failed("The test page hasn't finished saving. Check the printer's status above and Documents > PDF, then try again.")


def turn_on():
    """Switch CUPS's socket on as root (starchaser-admin printing-on); the password box says what it is for."""
    r = run(["pkexec", AREA, "printing-on"], timeout=120)
    if r.returncode == 126 or (r.returncode == 127 and not r.stdout.strip()):
        raise Canceled()
    try:
        result = json.loads(r.stdout)
    except ValueError:
        result = {}
    if r.returncode or not result.get("ok"):
        raise Failed(result.get("errors") or "Printing couldn't be turned on. Try again.")
    return {"ok": True, "on": True}


def no_printer():
    """True when no printer is added: the print dialog then offers only Print to File. An lpstat that failed or timed
    out, or found printing not running, doesn't know, so it isn't taken as no printer."""
    r = run(["lpstat", "-e"])
    if r.returncode or "not running" in r.stderr.lower():
        return False
    return not r.stdout.split()


def print_notice(off=False):
    """The dialog itself can only offer Print to File and a grayed-out Print, and says nothing (QA 20261106-1742 001).
    The notice's button opens Settings > Printers; the dialog lists a printer added there on its own. With printing
    turned off, the printers already added are still there: the notice says to turn printing on, not to add one.
    Keep the setup action until dismissed so someone reading slowly can use it while the print dialog stays open."""
    title = "Printing is turned off" if off else "No printer is set up"
    body = ("To print on paper, choose Turn on printing in Settings > Printers. " if off else
            "To print on paper, add your printer in Settings > Printers. ") + \
        "Print to File saves the document as a file instead of printing it."
    script = ('a=$(/bin/sh -c \'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/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 printer -t 0 -A printers="Open Printers" -h string:x-canonical-private-synchronous:starchaser-no-printer -w "$1" "$2"); [ "$a" = printers ] && exec starchaser settings printers')
    try:
        subprocess.Popen(["sh", "-c", script, "sh", title, body], stdin=subprocess.DEVNULL,
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
    except OSError:
        pass


def print_text():
    """Print standard input as plain text. Someone told to keep the recovery steps on paper presses one button; with no
    printer the notice that opens Settings > Printers appears, and the words below stay in the page."""
    text = sys.stdin.read()
    if not shutil.which("lp"):
        raise Failed("Printing isn't installed on this computer. Choose Save as a file instead.")
    if switched_off():
        print_notice(off=True)
        raise Failed("Printing is turned off. Turn it on in Settings > Printers, or choose Save as a file instead.")
    if no_printer():
        raise Failed("No printer is set up. Choose Save as a file, or add a printer in Settings > Printers.")
    try:
        r = subprocess.run(["lp", "-t", "Starchaser recovery instructions"], input=text, capture_output=True, text=True,
                           timeout=60)
    except (OSError, subprocess.TimeoutExpired):
        r = None
    if r is None or r.returncode:
        raise Failed("The steps couldn't be sent to the printer. Check its status in Settings > Printers, then try again.")
    return {"ok": True}


def alive(pid):
    try:
        os.kill(pid, 0)
    except ProcessLookupError:
        return False
    except OSError:
        pass
    return True


def watch_print(pid=None):
    """Hyprland's events while process PID runs (with no PID, until the session ends): each time a PRINT_APPS window
    titled Print opens (or gets that title), and no printer is set up, show print_notice() once for that window. The
    papers wrapper's watcher and the session's both see the viewer's dialog: the notice's key keeps it to one."""
    sig = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE", "")
    if not sig:
        return
    path = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")) / "hypr" / sig / ".socket2.sock"
    apps, told, buf = {}, set(), b""
    try:
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        s.settimeout(5)                                 # wake up now and then to see whether the viewer is gone
        s.connect(str(path))
    except OSError:
        return
    with s:
        while pid is None or alive(pid):
            try:
                data = s.recv(65536)
            except TimeoutError:
                continue
            except OSError:
                return
            if not data:
                return
            buf += data
            *lines, buf = buf.split(b"\n")
            for line in lines:
                event, _, args = line.decode("utf-8", "replace").partition(">>")
                if event == "openwindow":
                    addr, _ws, app, title = (args.split(",", 3) + ["", "", ""])[:4]
                    apps[addr] = app
                elif event == "windowtitlev2":
                    addr, _, title = args.partition(",")
                elif event == "closewindow":
                    apps.pop(args, None)
                    told.discard(args)
                    continue
                else:
                    continue
                if apps.get(addr) in PRINT_APPS and title == PRINT_TITLE and addr not in told:
                    told.add(addr)
                    if switched_off():
                        print_notice(off=True)
                    elif no_printer():
                        print_notice()


def auto_usb():
    # ipp-usb publishes local driverless printers on its dedicated high port range. A regular CUPS queue or
    # a service on somebody else's network can never enter this automatic path.
    listed = run(["ippfind", "_ipp._tcp", "--local", "--exec", "/usr/bin/printf", "%s\t%s\n", "{service_name}", "{service_uri}", ";"], timeout=10)
    existing = {printer["uri"] for printer in printer_list()}
    added = []
    for line in listed.stdout.splitlines():
        label_, sep, address = line.partition("\t")
        if not sep:
            continue
        try:
            uri = urlsplit(address)
            local = uri.hostname in ("localhost", "127.0.0.1", "::1") or uri.hostname == socket.gethostname() + ".local"
            if not local or uri.scheme not in ("ipp", "ipps") or not uri.port or not 60000 <= uri.port <= 65535 or address in existing:
                continue
        except ValueError:
            continue
        name = re.sub(r"[^a-zA-Z0-9_-]", "_", label_)[:80] or "USB_Printer"
        try:
            result = add(address, name)
        except (Failed, Canceled):
            continue
        if result.get("ok"):
            added.append(result)
            existing.add(address)
    return {"ok": True, "added": added}


def offer_printer(printer):
    script = 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; exec starchaser notify --credential-fd=3 "$@" 3<"$token"'
    answer = run(['sh', '-c', script, 'sh', '-a', 'Starchaser', '-i', 'printer',
                  '-A', 'add=Add', '-A', 'later=Not now', '-w', printer['name'] + ' found. Add it?', ''], timeout=86400)
    if answer.stdout.strip() == 'add':
        try:
            add(printer['uri'])
        except (Failed, Canceled):
            run(['starchaser', 'settings', 'printers'])


def discovered_offers(event, offered):
    if not event.startswith('+;') or not any(kind in event for kind in SERVICE_TYPES):
        return []
    zones = jread(ZONEMAP, {}).get('zones') or {}
    trusted = set(zones.get('trusted') or [])
    if not trusted or event.split(';')[1] not in trusted or switched_off():
        return []
    fresh = []
    for printer in found_printers(trusted, False, printer_list()):
        identity = printer['uri']
        if identity not in offered:
            offered.add(identity)
            fresh.append(printer)
    return fresh


def watch_network():
    import threading
    # Service events wake discovery. The Settings finder still honors any wider explicit firewall choices;
    # unsolicited offers are limited to trusted interfaces even when discovery is allowed elsewhere.
    offered = set()
    while True:
        try:
            with subprocess.Popen(['avahi-browse', '-a', '-p', '-l'], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) as monitor:
                for event in monitor.stdout:
                    for printer in discovered_offers(event, offered):
                        threading.Thread(target=offer_printer, args=(printer,), daemon=True).start()
        except (OSError, Failed):
            pass
        import time
        time.sleep(30)  # Restart a lost discovery connection without spinning.


def watch_usb():
    import threading
    threading.Thread(target=watch_network, daemon=True).start()
    import select
    import time
    with subprocess.Popen(["udevadm", "monitor", "--udev", "--subsystem-match=usb"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) as monitor:
        due = time.monotonic() + 3
        while monitor.poll() is None:
            if select.select([monitor.stdout], [], [], max(0, min(5, due - time.monotonic())))[0]:
                os.read(monitor.stdout.fileno(), 65536)
                due = time.monotonic() + 2
            if time.monotonic() >= due:
                try:
                    result = auto_usb()
                    for printer in result["added"]:
                        run(["starchaser", "notify", "-a", "Starchaser", "-i", "printer", "USB printer added", printer["name"] + " is ready. Print from any app."])
                except Failed:
                    pass  # Printing can be deliberately off; the next USB event checks again.
                due = time.monotonic() + 3600


def main(argv):
    safe_streams()
    if argv[:1] in (["-h"], ["--help"], ["help"]):
        print(__doc__.strip())
        return 0
    if not argv or argv[0] not in COMMANDS:
        return usage_error(PROG, f"unknown command {argv[0]!r}" if argv else "missing command", "COMMAND [ARG ...]",
                           list(COMMANDS))
    cmd, rest = argv[0], argv[1:]
    sizes = {"status": (0, 0), "printers": (0, 0), "found": (0, 0), "add": (1, 2), "remove": (1, 1),
             "default": (1, 1), "test": (1, 1), "turn-on": (0, 0), "print-text": (0, 0), "watch-print": (0, 1), "add-legacy": (3, 3), "auto-usb": (0, 0), "watch-usb": (0, 0), "drivers": (0, 1), "add-driver": (3, 3), "defaults": (3, 3), "details": (1, 1), "local": (0, 0), "resume": (1, 1), "cancel": (1, 1)}[cmd]
    if not sizes[0] <= len(rest) <= sizes[1]:
        return usage_error(PROG, f"wrong arguments for {cmd!r}", COMMANDS[cmd])
    if cmd == "watch-usb":
        watch_usb()
        return 0
    if cmd == "watch-print":
        if rest and not rest[0].isdigit():
            return usage_error(PROG, "PID must be a process number", COMMANDS[cmd])
        watch_print(int(rest[0]) if rest else None)
        return 0
    try:
        result = {"status": status, "printers": lambda: status(search=False), "found": found, "add": add,
                  "remove": remove, "default": make_default, "test": test_page, "turn-on": turn_on, "print-text": print_text, "add-legacy": add, "auto-usb": auto_usb, "drivers": drivers, "add-driver": add_driver, "defaults": set_defaults, "details": details, "local": local_printers, "resume": resume, "cancel": cancel_job}[cmd](*rest)
    except Canceled:
        print(json.dumps({"ok": False, "canceled": True, "errors": "No change made."}))
        return 1
    except Failed as e:
        print(json.dumps({"ok": False, "errors": str(e)}))
        return 1
    print(json.dumps(result))
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
