#!/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) and pdf2docx. The versions in use are
# listed in requirements.txt, published next to this file.
"""Zamienia plik PDF na DOCX biblioteką pdf2docx.

Użycie: pdf_to_docx.py WEJŚCIE.pdf WYJŚCIE.docx

Kody wyjścia:
  0 – plik zapisany,
  3 – PDF jest zaszyfrowany,
  4 – pliku nie da się odczytać jako PDF,
  1 – inny błąd konwersji.
"""

import logging
import sys


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

    logging.disable(logging.CRITICAL)
    import pymupdf
    from pdf2docx import Converter

    try:
        document = pymupdf.open(source)
    except Exception:
        return 4
    try:
        if document.needs_pass:
            return 3
        if document.page_count == 0:
            return 4
    finally:
        document.close()

    converter = Converter(source)
    try:
        # Jeden proces: limity pamięci i czasu obejmują wtedy całą konwersję.
        converter.convert(target, multi_processing=False)
    finally:
        converter.close()
    return 0


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