#!/usr/bin/env python3
"""Move files to the user trash. Used when the OS has no native `trash` CLI.

macOS: exec /usr/bin/trash.
Linux/WSL: Freedesktop XDG trash (~/.local/share/Trash).
"""

from __future__ import annotations

import datetime as dt
import os
import shutil
import sys
from pathlib import Path
from urllib.parse import quote


def _xdg_trash_root() -> Path:
    data_home = os.environ.get("XDG_DATA_HOME")
    if data_home:
        return Path(data_home) / "Trash"
    return Path.home() / ".local" / "share" / "Trash"


def _unique_trash_name(files_dir: Path, info_dir: Path, original: Path) -> str:
    name = original.name or "unnamed"
    candidate = name
    index = 1
    while (files_dir / candidate).exists() or (info_dir / f"{candidate}.trashinfo").exists():
        candidate = f"{original.stem} {index}{original.suffix}"
        index += 1
    return candidate


def _xdg_trash(path: Path) -> None:
    src = path.expanduser()
    src = src.resolve() if src.exists() else (src if src.is_absolute() else Path.cwd() / src)
    if not src.exists():
        raise FileNotFoundError(str(path))
    original = str(src)
    trash_root = _xdg_trash_root()
    files_dir = trash_root / "files"
    info_dir = trash_root / "info"
    files_dir.mkdir(parents=True, exist_ok=True)
    info_dir.mkdir(parents=True, exist_ok=True)
    dest_name = _unique_trash_name(files_dir, info_dir, src)
    dest = files_dir / dest_name
    shutil.move(str(src), str(dest))
    encoded = quote(original, safe="/")
    stamp = dt.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
    (info_dir / f"{dest_name}.trashinfo").write_text(
        f"[Trash Info]\nPath={encoded}\nDeletionDate={stamp}\n",
        encoding="utf-8",
    )


def main(argv: list[str]) -> int:
    paths = [a for a in argv[1:] if a != "--"]
    if not paths:
        print("usage: codex_trash.py FILE...", file=sys.stderr)
        return 2
    if sys.platform == "darwin":
        darwin = "/usr/bin/trash"
        if os.path.isfile(darwin) and os.access(darwin, os.X_OK):
            os.execv(darwin, [darwin, *paths])
    failed = 0
    for raw in paths:
        try:
            _xdg_trash(Path(raw))
        except OSError as exc:
            print(f"codex_trash: {raw}: {exc}", file=sys.stderr)
            failed = 1
    return failed


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))
