#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = ["Pillow==13.0.0"]
# ///
"""Remove the visible Gemini corner star using GemClean."""

import argparse
import http.client
import io
import json
import os
from pathlib import Path
import secrets
import struct
import sys
import tempfile
import time
import urllib.error
import urllib.request

API = "https://gemclean.app/api/model"
MIN_SIDE = 256
WINDOW = 320
CONTEXT_WINDOW = 512
MAX_PATCH = 512 * 1024


class Failure(Exception):
    def __init__(self, code, message, retry_after=None):
        super().__init__(message)
        self.code = code
        self.retry_after = retry_after


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args):
        return None


opener = urllib.request.build_opener(NoRedirect())


def request(path, method="GET", token=None, body=None, image=False, patch_length=None):
    headers = {"X-GemClean-Client": "agent-v1", "User-Agent": "GemClean-Skill/1"}
    if token:
        headers["X-Model-Token"] = token
    if body is not None:
        headers["Content-Type"] = "application/octet-stream"
        headers["X-GemClean-Patch-Length"] = str(patch_length)
    req = urllib.request.Request(API + path, data=body, headers=headers, method=method)
    try:
        with opener.open(req, timeout=90 if body is not None else 15) as response:
            if method == "DELETE":
                return
            limit = MAX_PATCH if image else 8192
            data = response.read(limit + 1)
            expected = "image/png" if image else "application/json"
            if len(data) > limit or response.headers.get_content_type() != expected:
                raise Failure("invalid_response", "GemClean returned an unexpected response.")
            if image:
                return data
            value = json.loads(data)
            if not isinstance(value, dict):
                raise ValueError()
            return value
    except urllib.error.HTTPError as error:
        with error:
            delay = error.headers.get("Retry-After", "")
            seconds = int(delay) if delay.isascii() and delay.isdigit() and len(delay) <= 8 else None
            if error.code == 429:
                raise Failure("rate_limited", "GemClean has reached its request limit.", seconds)
            if error.code in (400, 413, 415, 422):
                raise Failure("invalid_image", "GemClean could not process this watermark area.")
            if error.code == 409 and image:
                raise Failure("result_pending", "GemClean is still preparing the result.")
            if error.code in (404, 410):
                raise Failure("expired", "The GemClean job expired.")
            if 500 <= error.code <= 599 or error.code == 408:
                raise Failure("service_unavailable", f"GemClean returned HTTP {error.code}.", seconds)
            raise Failure("request_rejected", f"GemClean rejected the request (HTTP {error.code}).")
    except (OSError, EOFError, http.client.HTTPException) as error:
        raise Failure("service_unavailable", "Could not reach GemClean.") from error
    except (ValueError, UnicodeError) as error:
        raise Failure("invalid_response", "GemClean returned invalid job data.") from error


def restore(patch, diagnostic):
    config = request("/config")
    timestamp = config.get("serverTime")
    if not config.get("enabled") or config.get("processingWindowSize") != WINDOW or type(timestamp) is not int or not 0 < timestamp < 2**48:
        raise Failure("service_unavailable", "GemClean is unavailable.")
    job = f"/jobs/{timestamp:012x}{secrets.token_hex(26)}"
    token = secrets.token_hex(32)
    deadline = time.monotonic() + 600

    def wait(seconds):
        if time.monotonic() + seconds >= deadline:
            raise Failure("timeout", "GemClean did not finish within ten minutes.")
        time.sleep(seconds)

    def retrieve(path, image=False):
        while True:
            try:
                return request(path, token=token, image=image)
            except Failure as error:
                if error.code not in ("rate_limited", "service_unavailable", "result_pending"):
                    raise
                delay = max(5, error.retry_after or 0)
                if time.monotonic() + delay >= deadline:
                    raise
                wait(delay)

    # A lost POST acknowledgement can still leave a job in the queue.
    cancel_on_error = True
    try:
        try:
            status = request(job, "POST", token, patch + diagnostic, patch_length=len(patch))
        except Failure as error:
            if error.code in ("rate_limited", "invalid_image", "expired"):
                cancel_on_error = False
            raise
        while status.get("status") in ("queued", "running"):
            wait(3)
            status = retrieve(job)
        if status.get("status") != "succeeded":
            raise Failure("processing_failed", "GemClean did not complete the restoration.")
        return retrieve(job + "/result", image=True)
    except (Failure, KeyboardInterrupt):
        if cancel_on_error:
            try:
                request(job, "DELETE", token)
            except Failure:
                pass
        raise


def png_display_info(stream):
    from PIL.PngImagePlugin import PngInfo

    info = PngInfo()
    if stream.read(8) == b"\x89PNG\r\n\x1a\n":
        sizes = {b"sRGB": 1, b"gAMA": 4, b"cHRM": 32, b"cICP": 4}
        while len(header := stream.read(8)) == 8:
            length, kind = struct.unpack(">I4s", header)
            if kind in (b"IDAT", b"IEND"):
                break
            if sizes.get(kind) == length:
                info.add(kind, stream.read(length))
            else:
                stream.seek(length, os.SEEK_CUR)
            stream.seek(4, os.SEEK_CUR)  # CRC is checked by the PNG decoder.
    stream.seek(0)
    return info


def local_pixels(original):
    from PIL import ImageCms, ImageOps

    oriented = ImageOps.exif_transpose(original)
    alpha = "A" in oriented.getbands() or "transparency" in oriented.info
    profile = original.info.get("icc_profile")
    if profile and oriented.mode in ("CMYK", "L", "LA", "1"):
        color = oriented if oriented.mode == "CMYK" else oriented.convert("L")
        target = ImageCms.createProfile("sRGB")
        try:
            canvas = ImageCms.profileToProfile(color, io.BytesIO(profile), target, outputMode="RGB")
        except ImageCms.PyCMSError as error:
            raise Failure("invalid_image", "Could not convert the image's embedded color profile.") from error
        if alpha:
            canvas.putalpha(oriented.convert("RGBA").getchannel("A"))
        profile = canvas.info.get("icc_profile")
    else:
        canvas = oriented.convert("RGBA" if alpha else "RGB")
    canvas.info.clear()
    return canvas, profile


def remove(source, output):
    try:
        from PIL import Image
    except ImportError as error:
        raise Failure("missing_dependency", "Run with uv run --script or install Pillow in a virtual environment.") from error
    if output.suffix.lower() != ".png":
        raise Failure("invalid_output", "Choose an output filename ending in .png.")
    if os.path.lexists(output):
        raise Failure("output_exists", f"Output already exists: {output}")
    if not output.parent.is_dir():
        raise Failure("invalid_output", "The output directory does not exist.")
    try:
        with source.open("rb") as stream:
            source_stat = os.fstat(stream.fileno())
            if source_stat.st_size > 20 * 1024**2:
                raise Failure("invalid_image", "Choose an image up to 20 MiB.")
            header = stream.read(25)
            if header.startswith(b"\x89PNG\r\n\x1a\n") and header[24:25] == b"\x10":
                raise Failure("invalid_image", "Choose an 8-bit PNG or a JPEG or WebP image.")
            stream.seek(0)
            png_info = png_display_info(stream)
            with Image.open(stream, formats=("PNG", "JPEG", "WEBP")) as original:
                w, h = original.size
                if min(w, h) < MIN_SIDE or max(w, h) > 16384 or w * h > 40_000_000:
                    raise Failure("invalid_image", "Use 256–16384 pixels per side and at most 40 megapixels.")
                if getattr(original, "n_frames", 1) != 1:
                    raise Failure("invalid_image", "Choose a still image.")
                canvas, profile = local_pixels(original)
    except (OSError, ValueError, SyntaxError, Image.DecompressionBombError) as error:
        raise Failure("invalid_image", "Could not read a still PNG, JPEG or WebP file.") from error
    w, h = canvas.size
    diagnostic = canvas.crop((max(0, w - CONTEXT_WINDOW), max(0, h - CONTEXT_WINDOW), w, h))
    corner = canvas.crop((max(0, w - WINDOW), max(0, h - WINDOW), w, h))
    if canvas.mode == "RGBA" and corner.getchannel("A").getextrema() != (255, 255):
        raise Failure("invalid_image", "The bottom-right corner must be opaque.")
    # Keep native pixels aligned to the bottom-right. Extend edges only for a short side.
    padded = Image.new("RGB", (WINDOW, WINDOW))
    left, top = WINDOW - corner.width, WINDOW - corner.height
    padded.paste(corner.convert("RGB"), (left, top))
    if left:
        padded.paste(padded.crop((left, top, left + 1, WINDOW)).resize((left, corner.height), Image.Resampling.NEAREST), (0, top))
    if top:
        padded.paste(padded.crop((0, top, WINDOW, top + 1)).resize((WINDOW, top), Image.Resampling.NEAREST), (0, 0))
    encoded = io.BytesIO()
    padded.save(encoded, "PNG")
    diagnostic_bytes = io.BytesIO()
    diagnostic.save(diagnostic_bytes, "PNG")
    # Check local write access before submission. Publish the complete PNG without replacing a racing writer.
    with tempfile.TemporaryDirectory(prefix=".gemclean-", dir=output.parent) as work:
        ready = Path(work) / "result.png"
        mode = 0o600 | (source_stat.st_mode & 0o044)
        with os.fdopen(os.open(ready, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode), "wb") as stream:
            data = restore(encoded.getvalue(), diagnostic_bytes.getvalue())
            try:
                with Image.open(io.BytesIO(data), formats=("PNG",)) as result:
                    if result.size != (WINDOW, WINDOW) or getattr(result, "n_frames", 1) != 1:
                        raise ValueError()
                    canvas.paste(result.convert("RGB"), (w - WINDOW, h - WINDOW))
            except (OSError, ValueError, SyntaxError, Image.DecompressionBombError) as error:
                raise Failure("invalid_response", "GemClean returned an invalid corner image.") from error
            canvas.save(stream, "PNG", icc_profile=profile, pnginfo=png_info)
        try:
            os.link(ready, output)
        except FileExistsError as error:
            raise Failure("output_exists", f"Output already exists: {output}") from error
    return {"output": str(output.absolute()), "width": w, "height": h}


def main():
    parser = argparse.ArgumentParser(prog="gemclean", description=__doc__)
    command = parser.add_subparsers(dest="command", required=True).add_parser("remove")
    command.add_argument("input", type=Path)
    command.add_argument("-o", "--output", type=Path, help="new PNG path (default: <input>.clean.png)")
    command.add_argument("--json", action="store_true", help="emit structured output and errors")
    args = parser.parse_args()
    try:
        result = remove(args.input, args.output or args.input.with_suffix(".clean.png"))
        print(json.dumps(result) if args.json else result["output"])
        return 0
    except (Failure, OSError, KeyboardInterrupt) as error:
        code = error.code if isinstance(error, Failure) else "cancelled" if isinstance(error, KeyboardInterrupt) else "file_error"
        details = {"error": code, "message": str(error) or "Cancelled."}
        if isinstance(error, Failure) and error.retry_after is not None:
            details["retry_after_seconds"] = error.retry_after
        print(json.dumps(details) if args.json else details["message"], file=sys.stderr)
        return 1


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