#!/usr/bin/env python3
# lupa-image-search - Google Lens reverse image search helper for Lupa OCR.
#
# Light & fast: uploads the image to a single trusted host
# (litterbox.catbox.moe), which always returns the raw image URL, then opens
# Google Lens with it. If the upload fails, copies the file to the clipboard
# and opens Lens for manual paste.
#
# Usage: lupa-image-search [--debug] /path/to/image.png
# SPDX-License-Identifier: GPL-3.0-or-later

import os
import subprocess
import sys
import time
import urllib.parse

TIMEOUT = 15
DEBUG = "--debug" in [a for a in sys.argv[1:]]


def dbg(msg):
    if DEBUG:
        print(f"[debug] {msg}", flush=True)


def notify(msg, icon="dialog-information"):
    try:
        subprocess.Popen(
            ["notify-send", "-t", "3000", "-i", icon, "Lupa OCR", msg],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
    except Exception:
        pass


def upload_litterbox(path):
    t0 = time.monotonic()
    r = subprocess.run(
        ["curl", "-s", "--max-time", str(TIMEOUT),
         "-F", "reqtype=fileupload", "-F", "time=72h",
         "-F", f"fileToUpload=@{path}",
         "https://litterbox.catbox.moe/resources/internals/api.php"],
        capture_output=True,
        text=True,
    )
    url = (r.stdout or "").strip()
    dbg(f"litterbox respondeu em {time.monotonic()-t0:.2f}s: {url[:80]}")
    if not url.startswith("http"):
        raise RuntimeError(f"litterbox falhou: {url[:60] or 'resposta vazia'}")
    return url


def open_lens(url):
    lens_url = "https://lens.google.com/uploadbyurl?url=" + urllib.parse.quote(url)
    subprocess.Popen(["xdg-open", lens_url])


def cleanup_temp(path):
    if os.path.basename(path) == "lupa-ocr-capture.png":
        try:
            os.remove(path)
            dbg("temp removido")
        except OSError:
            pass


def main():
    args = [a for a in sys.argv[1:] if a != "--debug"]
    if not args:
        print("usage: lupa-image-search [--debug] <image>")
        return 1
    path = args[0]
    if not os.path.isfile(path):
        notify("Imagem não encontrada", "dialog-error")
        return 1

    try:
        notify("Enviando imagem para busca...", "image-loading")
        url = upload_litterbox(path)
        dbg(f"ok: {url}")
        open_lens(url)
        notify("Abrindo Google Lens...", "emblem-ok")
    except Exception as e:
        dbg(f"upload falhou: {e}")
        try:
            subprocess.run(["wl-copy", "--type", "image/png", path],
                           capture_output=True)
        except Exception:
            try:
                subprocess.run(["wl-copy", path], capture_output=True)
            except Exception:
                pass
        notify("Upload falhou - imagem copiada, cole no Lens", "dialog-warning")
        subprocess.Popen(["xdg-open", "https://lens.google.com/"])

    cleanup_temp(path)
    return 0


if __name__ == "__main__":
    sys.exit(main())
