#!/usr/bin/python3
# blob:summary=Show printer toner and queue, cancel or pause jobs, print a test page, and scan documents
# blob:args=[status|summary|select <printer>|cancel <job>|cancel-all|pause|resume|test-page|web|settings|set <key> <value>|scanners|scan|scan-cancel|open-last|folder]
# blob:group=system

from __future__ import annotations

import getpass
import json
import os
import shutil
import signal
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from typing import Any

BLOB_PATH = Path(os.environ.get("BLOB_PATH", str(Path.home() / ".local" / "share" / "blob")))
sys.path.insert(0, str(BLOB_PATH / "default" / "printer"))

import discovery
import ipp
import scanner

RUNTIME_DIRECTORY = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "blob"
RUNTIME_FILE = RUNTIME_DIRECTORY / "printer.json"
STATE_DIRECTORY = Path(os.environ.get("XDG_STATE_HOME", str(Path.home() / ".local" / "state"))) / "blob"
SETTINGS_FILE = STATE_DIRECTORY / "printer.json"
DEVICE_CACHE_SECONDS = 600
TEST_PAGE_FILES = ("/usr/share/cups/data/default-testpage.pdf", "/usr/share/cups/data/testprint")
PRINTER_ATTRIBUTES = [
  "printer-state", "printer-state-reasons", "printer-make-and-model", "media-default",
  "marker-names", "marker-levels", "marker-colors", "marker-types",
]
JOB_ATTRIBUTES = [
  "job-id", "job-name", "job-state", "job-printer-uri", "job-originating-user-name",
  "job-impressions-completed", "job-media-sheets-completed",
]
SCAN_CHOICES = {
  "source": ("auto", "glass", "feeder", "duplex"),
  "colour": ("colour", "grey", "bw"),
  "size": ("a4", "letter", "legal", "max"),
  "format": ("pdf", "jpeg"),
  "open": ("on", "off"),
}
DEFAULT_SCAN_SETTINGS = {"source": "auto", "colour": "colour", "dpi": "300", "size": "a4", "format": "pdf", "open": "off"}
PRINTER_STATES = {3: "Ready", 4: "Printing", 5: "Stopped"}
JOB_STATES = {3: "Waiting", 4: "Held", 5: "Printing", 6: "Stopped"}
REASON_LABELS = {
  "media-empty": "Out of paper",
  "media-needed": "Load paper",
  "media-jam": "Paper jam",
  "toner-low": "Toner low",
  "toner-empty": "Out of toner",
  "marker-supply-low": "Toner low",
  "marker-supply-empty": "Out of toner",
  "door-open": "Cover open",
  "cover-open": "Cover open",
  "input-tray-missing": "Paper tray missing",
  "offline": "Offline",
  "paused": "Paused",
  "connecting-to-device": "Connecting",
}
MEDIA_NAMES = {"iso_a4": "A4", "iso_a5": "A5", "na_letter": "Letter", "na_legal": "Legal", "na_executive": "Executive"}


def run(command: list[str], timeout: float = 15) -> subprocess.CompletedProcess:
  try:
    return subprocess.run(command, capture_output=True, text=True, timeout=timeout)
  except (OSError, subprocess.TimeoutExpired) as error:
    return subprocess.CompletedProcess(command, 1, "", str(error))


def read_json(path: Path) -> dict[str, Any]:
  try:
    data = json.loads(path.read_text(encoding="utf-8"))
    return data if isinstance(data, dict) else {}
  except (OSError, ValueError):
    return {}


def write_json(path: Path, data: dict[str, Any]) -> None:
  path.parent.mkdir(parents=True, exist_ok=True)
  temporary = path.with_suffix(".tmp")
  temporary.write_text(json.dumps(data) + "\n", encoding="utf-8")
  temporary.replace(path)


def update_runtime(**changes: Any) -> dict[str, Any]:
  data = read_json(RUNTIME_FILE)
  data.update(changes)
  write_json(RUNTIME_FILE, data)
  return data


def scan_settings() -> dict[str, str]:
  saved = read_json(SETTINGS_FILE).get("scan", {})
  settings = dict(DEFAULT_SCAN_SETTINGS)
  for key, value in saved.items():
    if key in settings:
      settings[key] = str(value)
  return settings


def chosen_printer(names: list[str]) -> str:
  saved = read_json(SETTINGS_FILE).get("printer", "")
  if saved in names:
    return saved
  default = discovery.default_printer()
  if default in names:
    return default
  return names[0] if names else ""


def device_info(printer: str) -> dict[str, str]:
  cached = read_json(RUNTIME_FILE).get("device", {})
  if cached.get("printer") == printer and time.time() - cached.get("time", 0) < DEVICE_CACHE_SECONDS and cached.get("uri") and "name" in cached:
    return cached
  device = discovery.device_for(printer)
  device.update({"printer": printer, "time": time.time()})
  update_runtime(device=device)
  return device


def media_name(media: str) -> str:
  prefix = "_".join(media.split("_")[:2])
  return MEDIA_NAMES.get(prefix, media.split("_")[1].upper() if media.count("_") >= 2 else media)


def reason_text(reasons: list[str]) -> list[str]:
  labels = []
  for reason in reasons:
    base = reason
    for suffix in ("-error", "-warning", "-report"):
      base = base.removesuffix(suffix)
    label = REASON_LABELS.get(base)
    if label and label not in labels:
      labels.append(label)
  return labels


def toner_list(attributes: dict[str, list[Any]]) -> list[dict[str, Any]]:
  names = attributes.get("marker-names", [])
  levels = attributes.get("marker-levels", [])
  colors = attributes.get("marker-colors", [])
  types = attributes.get("marker-types", [])
  toners = []
  for index, name in enumerate(names):
    kind = str(types[index]) if index < len(types) else "toner"
    if "waste" in kind or "waste" in str(name).lower():
      continue
    level = levels[index] if index < len(levels) and isinstance(levels[index], int) else -1
    color = str(colors[index]).split("#")[1] if index < len(colors) and "#" in str(colors[index]) else ""
    toners.append({"name": str(name), "level": level if level >= 0 else None, "color": "#" + color[:6] if color else ""})
  return toners


def query_printer(printer: str, device: dict[str, str]) -> tuple[dict[str, list[Any]], str]:
  uris = [uri for uri in (device.get("uri", ""), f"ipp://localhost/printers/{printer}") if uri]
  error = ""
  for uri in uris:
    try:
      attributes = ipp.printer_attributes(uri, PRINTER_ATTRIBUTES)
    except ipp.IppError as failure:
      error = str(failure)
      continue
    if attributes:
      return attributes, ""
  return {}, error


def job_list(printer: str) -> list[dict[str, Any]]:
  try:
    raw_jobs = ipp.jobs("ipp://localhost/", getpass.getuser(), JOB_ATTRIBUTES)
  except ipp.IppError:
    return []
  jobs = []
  for job in raw_jobs:
    printer_uri = str((job.get("job-printer-uri") or [""])[0])
    if not printer_uri.endswith("/printers/" + printer):
      continue
    state = (job.get("job-state") or [3])[0]
    pages_done = (job.get("job-impressions-completed") or job.get("job-media-sheets-completed") or [0])[0]
    jobs.append({
      "id": (job.get("job-id") or [0])[0],
      "title": str((job.get("job-name") or ["Untitled"])[0]),
      "user": str((job.get("job-originating-user-name") or [""])[0]),
      "state": JOB_STATES.get(state, "Waiting"),
      "page": pages_done + 1 if state == 5 else 0,
    })
  return jobs


def printer_paused(printer: str) -> bool:
  return "disabled" in run(["lpstat", "-p", printer]).stdout


def scans_directory() -> Path:
  documents = run(["xdg-user-dir", "DOCUMENTS"]).stdout.strip() or str(Path.home() / "Documents")
  directory = Path(documents) / "Scans"
  directory.mkdir(parents=True, exist_ok=True)
  return directory


def process_alive(pid: Any) -> bool:
  if not isinstance(pid, int):
    return False
  try:
    os.kill(pid, 0)
  except OSError:
    return False
  return True


def scan_state() -> dict[str, Any]:
  runtime = read_json(RUNTIME_FILE)
  scan = runtime.get("scan", {})
  if scan.get("scanning") and not process_alive(scan.get("pid")):
    scan["scanning"] = False
    scan["error"] = scan.get("error") or "The scan stopped unexpectedly"
    update_runtime(scan=scan)
  files = [file for file in scan.get("files", []) if Path(file).is_file()]
  if not files:
    newest = sorted(scans_directory().glob("Scan *"), key=lambda path: path.stat().st_mtime, reverse=True)
    files = [str(newest[0])] if newest else []
  scanner_cache = runtime.get("scanner", {})
  if scanner_cache.get("device") and not scanner.usable(scanner_cache["device"]):
    scanner_cache = {}
  return {
    "available": scanner.available(),
    "scanning": bool(scan.get("scanning")),
    "startedAt": scan.get("startedAt", 0),
    "error": scan.get("error", ""),
    "lastFile": files[0] if files else "",
    "lastName": Path(files[0]).name if files else "",
    "device": scanner_cache.get("device", ""),
    "description": scanner_cache.get("description", ""),
    "options": scanner_cache.get("options", {}),
    "searched": bool(scanner_cache),
    "settings": scan_settings(),
    "folder": str(scans_directory()),
  }


def status() -> dict[str, Any]:
  names = discovery.printer_names()
  printer = chosen_printer(names)
  result: dict[str, Any] = {
    "installed": shutil.which("lpstat") is not None,
    "printers": names,
    "printer": printer,
    "reachable": False,
    "state": "",
    "problems": [],
    "model": "",
    "media": "",
    "toners": [],
    "jobs": [],
    "paused": False,
    "webUrl": "",
    "error": "",
    "scan": scan_state(),
  }
  if not printer:
    return result
  device = device_info(printer)
  attributes, error = query_printer(printer, device)
  result["webUrl"] = device.get("webUrl", "")
  result["jobs"] = job_list(printer)
  result["paused"] = printer_paused(printer)
  if not attributes:
    result["error"] = "The printer did not answer" + (f": {error}" if error else "")
    return result
  state = (attributes.get("printer-state") or [3])[0]
  result["reachable"] = True
  result["state"] = "Paused" if result["paused"] else PRINTER_STATES.get(state, "Ready")
  result["problems"] = [label for label in reason_text([str(reason) for reason in attributes.get("printer-state-reasons", [])]) if label != "Paused"]
  result["model"] = device.get("name") or str((attributes.get("printer-make-and-model") or [""])[0])
  result["media"] = media_name(str((attributes.get("media-default") or [""])[0]))
  result["toners"] = toner_list(attributes)
  return result


def summary() -> dict[str, Any]:
  names = discovery.printer_names()
  jobs = [line for line in run(["lpstat", "-o"]).stdout.splitlines() if line.strip()]
  return {"present": bool(names), "jobs": len(jobs), "scanning": bool(read_json(RUNTIME_FILE).get("scan", {}).get("scanning"))}


def current_printer() -> str:
  printer = chosen_printer(discovery.printer_names())
  if not printer:
    print("No printer found", file=sys.stderr)
    sys.exit(1)
  return printer


def report(process: subprocess.CompletedProcess, failure: str) -> int:
  if process.returncode != 0:
    detail = (process.stderr or "").strip().splitlines()
    print(failure + (": " + detail[-1] if detail else ""), file=sys.stderr)
    return 1
  return 0


def open_detached(target: str) -> None:
  subprocess.Popen(["xdg-open", target], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)


def set_scan_setting(key: str, value: str) -> int:
  if key == "dpi" and not value.isdigit():
    print("dpi must be a number", file=sys.stderr)
    return 2
  if key != "dpi" and value not in SCAN_CHOICES.get(key, ()):
    print(f"Unknown scan setting {key} {value}", file=sys.stderr)
    return 2
  settings = read_json(SETTINGS_FILE)
  settings.setdefault("scan", {})[key] = value
  write_json(SETTINGS_FILE, settings)
  return 0


def find_scanner() -> dict[str, Any]:
  if not scanner.available():
    print("Scanning needs the sane and sane-airscan packages", file=sys.stderr)
    sys.exit(1)
  device = scanner.pick_device(scanner.find_devices(), chosen_printer(discovery.printer_names()))
  if device is None:
    update_runtime(scanner={"device": "", "description": "", "options": {}})
    print("No scanner found", file=sys.stderr)
    sys.exit(1)
  cache = {"device": device["device"], "description": device["description"], "options": scanner.device_options(device["device"])}
  update_runtime(scanner=cache)
  return cache


def scan() -> int:
  current = read_json(RUNTIME_FILE).get("scan", {})
  if current.get("scanning") and process_alive(current.get("pid")):
    return 0
  os.setpgrp()
  update_runtime(scan={"scanning": True, "pid": os.getpid(), "startedAt": int(time.time() * 1000), "error": "", "files": []})
  cache = read_json(RUNTIME_FILE).get("scanner", {})
  try:
    if not scanner.usable(cache.get("device", "")):
      cache = find_scanner()
    settings = scan_settings()
    destination = scans_directory() / time.strftime("Scan %Y-%m-%d %H-%M-%S")
    RUNTIME_DIRECTORY.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(dir=RUNTIME_DIRECTORY, prefix="scan-") as work_directory:
      files = scanner.scan(cache["device"], cache["options"], settings, Path(work_directory), destination)
  except scanner.ScanError as error:
    update_runtime(scan={"scanning": False, "pid": None, "error": str(error), "files": []})
    return 1
  except SystemExit:
    update_runtime(scan={"scanning": False, "pid": None, "error": "No scanner found", "files": []})
    return 1
  update_runtime(scan={"scanning": False, "pid": None, "error": "", "files": [str(file) for file in files]})
  if settings["open"] == "on" and files:
    open_detached(str(files[0]))
  return 0


def cancel_scan() -> int:
  current = read_json(RUNTIME_FILE).get("scan", {})
  pid = current.get("pid")
  if process_alive(pid):
    try:
      os.killpg(pid, signal.SIGTERM)
    except OSError:
      pass
  update_runtime(scan={"scanning": False, "pid": None, "error": "Scan cancelled", "files": []})
  return 0


def main(arguments: list[str]) -> int:
  action = arguments[0] if arguments else "status"
  value = arguments[1] if len(arguments) > 1 else ""
  extra = arguments[2] if len(arguments) > 2 else ""
  if action == "status":
    print(json.dumps(status()))
  elif action == "summary":
    print(json.dumps(summary()))
  elif action == "select" and value:
    settings = read_json(SETTINGS_FILE)
    settings["printer"] = value
    write_json(SETTINGS_FILE, settings)
  elif action == "cancel" and value.isdigit():
    return report(run(["cancel", f"{current_printer()}-{value}"]), "Could not cancel the job")
  elif action == "cancel-all":
    return report(run(["cancel", "-u", getpass.getuser(), current_printer()]), "Could not cancel your jobs")
  elif action == "pause":
    return report(run(["cupsdisable", current_printer()]), "Could not pause the printer")
  elif action == "resume":
    return report(run(["cupsenable", current_printer()]), "Could not resume the printer")
  elif action == "test-page":
    test_page = next((file for file in TEST_PAGE_FILES if Path(file).is_file()), "")
    if not test_page:
      print("No CUPS test page found", file=sys.stderr)
      return 1
    return report(run(["lp", "-d", current_printer(), "-t", "Test page", test_page]), "Could not print the test page")
  elif action == "web":
    url = device_info(current_printer()).get("webUrl", "")
    if not url:
      print("Could not find the printer's address", file=sys.stderr)
      return 1
    open_detached(url)
  elif action == "settings":
    subprocess.Popen(["system-config-printer"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
  elif action == "set" and value and extra:
    return set_scan_setting(value, extra)
  elif action == "scanners":
    find_scanner()
  elif action == "scan":
    return scan()
  elif action == "scan-cancel":
    return cancel_scan()
  elif action == "open-last":
    last = scan_state()["lastFile"]
    if last:
      open_detached(last)
  elif action == "folder":
    open_detached(str(scans_directory()))
  else:
    print("Usage: blob-printer [status|summary|select <printer>|cancel <job>|cancel-all|pause|resume|test-page|web|settings|set <key> <value>|scanners|scan|scan-cancel|open-last|folder]", file=sys.stderr)
    return 2
  return 0


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