#!/usr/bin/env python3
"""Store one clipboard selection in cliphist, skipping secrets and large items.

wl-paste --watch invokes this once per clipboard change and passes the selected
bytes on stdin. The KDE password hint is checked first so vault passwords never
reach history; oversized items are drained and dropped so the watcher cannot
block.
"""

from __future__ import annotations

import os
import subprocess
import sys

HINT = "x-kde-passwordManagerHint"
CHUNK = 64 * 1024


def _is_sensitive() -> bool:
    # wl-paste 2.3 sets this for the exact offer that produced stdin, so it is
    # race-free. It also covers the KDE password hint that wl-copy --sensitive
    # sets. Fall back to inspecting types for older wl-clipboard builds.
    state = os.environ.get("CLIPBOARD_STATE", "").strip().casefold()
    if state:
        return state == "sensitive"

    try:
        result = subprocess.run(
            ["wl-paste", "--list-types"],
            capture_output=True,
            timeout=2,
            check=False,
        )
    except (OSError, subprocess.SubprocessError):
        return True
    if result.returncode != 0:
        return True
    types = result.stdout.decode("utf-8", errors="replace").splitlines()
    return any(kind.strip() == HINT for kind in types)


def _read_limited(stream, limit: int) -> bytes | None:
    chunks: list[bytes] = []
    total = 0
    too_big = False
    while True:
        chunk = stream.read(CHUNK)
        if not chunk:
            break
        total += len(chunk)
        if total > limit:
            too_big = True
            chunks.clear()
            continue
        chunks.append(chunk)
    if too_big:
        return None
    return b"".join(chunks)


def _number(value: str, fallback: int) -> int:
    try:
        parsed = int(value)
    except (TypeError, ValueError):
        return fallback
    return parsed if parsed > 0 else fallback


def main(argv: list[str] | None = None) -> int:
    arguments = list(sys.argv[1:] if argv is None else argv)
    max_items = _number(arguments[0], 100) if arguments else 100
    max_bytes = (
        _number(arguments[1], 5 * 1024 * 1024)
        if len(arguments) > 1
        else 5 * 1024 * 1024
    )

    os.umask(0o077)
    sensitive = _is_sensitive()
    data = _read_limited(sys.stdin.buffer, max_bytes)
    if sensitive or data is None or not data:
        return 0

    try:
        subprocess.run(
            ["cliphist", "-max-items", str(max_items), "store"],
            input=data,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            timeout=10,
            check=False,
        )
    except (OSError, subprocess.SubprocessError):
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
