#!/usr/bin/env python3
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# Copyright (C) 2026 Szymon Kubik (Web Tools Online)
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU Affero General Public License for more details:
# https://www.gnu.org/licenses/agpl-3.0.html
#
# This script imports PyMuPDF (AGPL-3.0). The version in use is listed in
# requirements.txt, published next to this file.
"""Wyodrębnia obrazy z pliku PDF do archiwum ZIP.

Użycie: extract_images.py WEJŚCIE.pdf WYJŚCIE.zip

Zdjęcia JPG trafiają do archiwum bez ponownej kompresji. Pozostałe obrazy są
zapisywane jako PNG, razem z przezroczystością. Ten sam obraz użyty na kilku
stronach trafia do archiwum raz, a bardzo małe obrazy (ikony, linie) są pomijane.

Kody wyjścia:
  0 – archiwum zapisane,
  3 – PDF jest zaszyfrowany,
  4 – pliku nie da się odczytać jako PDF,
  5 – w dokumencie nie ma obrazów,
  1 – inny błąd.
"""

import sys
import zipfile

# Obrazy o krótszym boku poniżej tej liczby pikseli to ikony i linie.
MIN_SIDE = 48
# Ograniczenia chroniące serwer przed dokumentem z tysiącami obrazów.
MAX_IMAGES = 500
MAX_TOTAL_BYTES = 200 * 1024 * 1024


def image_bytes(pymupdf, document, xref, smask):
    """Zwraca (rozszerzenie, dane) jednego obrazu albo None, gdy nie da się go odczytać."""
    try:
        info = document.extract_image(xref)
    except Exception:
        return None
    if not info:
        return None
    # Zdjęcie JPG w przestrzeni szarości albo RGB i bez maski: bajty z dokumentu.
    if info.get("ext") in ("jpeg", "jpg") and not smask and info.get("colorspace") in (1, 3):
        return "jpg", info["image"]
    try:
        pixmap = pymupdf.Pixmap(document, xref)
        if smask:
            # Przezroczystość jest w PDF osobnym obrazem: łączymy ją z kolorami.
            mask = pymupdf.Pixmap(document, smask)
            if pixmap.alpha:
                pixmap = pymupdf.Pixmap(pixmap, 0)
            if (mask.width, mask.height) == (pixmap.width, pixmap.height):
                pixmap = pymupdf.Pixmap(pixmap, mask)
        if pixmap.colorspace is None or pixmap.colorspace.n not in (1, 3):
            # CMYK i inne przestrzenie barw: PNG zapisuje tylko szarość i RGB.
            pixmap = pymupdf.Pixmap(pymupdf.csRGB, pixmap)
        return "png", pixmap.tobytes("png")
    except Exception:
        return None


def main() -> int:
    if len(sys.argv) != 3:
        print(__doc__, file=sys.stderr)
        return 2
    source, target = sys.argv[1], sys.argv[2]

    import pymupdf

    pymupdf.TOOLS.mupdf_display_errors(False)
    try:
        document = pymupdf.open(source)
    except Exception:
        return 4
    try:
        if document.needs_pass:
            return 3
        if document.page_count == 0:
            return 4

        seen = set()
        count = 0
        total = 0
        with zipfile.ZipFile(target, "w", zipfile.ZIP_STORED) as archive:
            for page_index in range(document.page_count):
                for item in document.get_page_images(page_index, full=True):
                    xref, smask, width, height = item[0], item[1], item[2], item[3]
                    if xref in seen:
                        continue
                    seen.add(xref)
                    if min(width, height) < MIN_SIDE:
                        continue
                    found = image_bytes(pymupdf, document, xref, smask)
                    if found is None:
                        continue
                    extension, data = found
                    total += len(data)
                    if count >= MAX_IMAGES or total > MAX_TOTAL_BYTES:
                        break
                    count += 1
                    archive.writestr(f"image-{count:03d}.{extension}", data)
                else:
                    continue
                break
        return 0 if count > 0 else 5
    finally:
        document.close()


if __name__ == "__main__":
    try:
        sys.exit(main())
    except Exception as error:  # noqa: BLE001 - wynik to kod wyjścia, nie ślad błędu
        print(f"extract_images: {type(error).__name__}", file=sys.stderr)
        sys.exit(1)
