#!/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.
"""Przenosi tabele z pliku PDF do arkusza XLSX.

Użycie: pdf_to_xlsx.py WEJŚCIE.pdf WYJŚCIE.xlsx

Tabele wykrywa PyMuPDF. Każda tabela trafia do osobnego arkusza; tabela, która
ciągnie się przez kilka stron, jest sklejana w jeden arkusz. Liczby zapisujemy
jako liczby. Plik XLSX powstaje bez dodatkowych bibliotek: to archiwum ZIP
z kilkoma plikami XML.

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

import re
import sys
import zipfile
from xml.sax.saxutils import escape

# Ograniczenia chronią serwer przed dokumentem z tysiącami stron albo tabel.
MAX_PAGES = 200
MAX_SHEETS = 100
# Tabela bez linii musi mieć tyle wierszy i tyle wypełnionych komórek, żeby nie
# pomylić jej ze zwykłym akapitem ułożonym w wiersze.
TEXT_MIN_ROWS = 3
TEXT_MIN_FILLED = 0.6
# Ciąg dalszy tabeli zaczyna się w górnej części następnej strony.
CONTINUATION_TOP = 0.3

SPACES = re.compile(r"[\s  ]+")
CURRENCY = re.compile(r"^(?:zł|PLN|€|EUR|\$|USD|£|GBP)\s*|\s*(?:zł|PLN|€|EUR|\$|USD|£|GBP)$")
# Grupy tysięcy oddzielone spacją, kropką, przecinkiem albo apostrofem.
NUMBER = re.compile(r"^[-+−]?\d{1,3}(?:[ .,']\d{3})*(?:[.,]\d+)?$|^[-+−]?\d+(?:[.,]\d+)?$")


def clean(value):
    """Tekst komórki w jednym wierszu, bez zbędnych odstępów."""
    if value is None:
        return ""
    return SPACES.sub(" ", str(value)).strip()


def decimal_separator(cells):
    """Znak dziesiętny dokumentu: ten, który w liczbach występuje jednoznacznie."""
    comma = 0
    dot = 0
    for cell in cells:
        text = CURRENCY.sub("", cell).strip()
        if not NUMBER.match(text):
            continue
        text = text.replace(" ", "")
        last_comma = text.rfind(",")
        last_dot = text.rfind(".")
        if last_comma >= 0 and last_dot >= 0:
            if last_comma > last_dot:
                comma += 2
            else:
                dot += 2
        elif last_comma >= 0 and len(text) - last_comma - 1 != 3:
            comma += 1
        elif last_dot >= 0 and len(text) - last_dot - 1 != 3:
            dot += 1
    if comma == dot:
        return None
    return "," if comma > dot else "."


def to_number(cell, separator):
    """Liczba zapisana w komórce albo None, gdy komórka nie jest liczbą."""
    text = CURRENCY.sub("", cell).strip()
    if not NUMBER.match(text):
        return None
    compact = text.replace(" ", "")
    digits = re.sub(r"\D", "", compact)
    # Numery kont, kody i identyfikatory to nie liczby: zera na początku mają znaczenie.
    if len(digits) > 15:
        return None
    whole = re.split(r"[.,]", compact.lstrip("-+−"))[0]
    if len(whole) > 1 and whole.startswith("0"):
        return None
    marks = [char for char in compact if char in ".,'"]
    if not marks:
        normal = compact
    else:
        last = max(compact.rfind(","), compact.rfind("."))
        after = len(compact) - last - 1
        kinds = set(marks)
        if len(kinds) > 1:
            # Dwa różne znaki: ostatni rozdziela część dziesiętną.
            decimal = compact[last]
        elif len(marks) > 1:
            # Ten sam znak kilka razy: to grupy tysięcy.
            decimal = None
        elif after != 3:
            decimal = marks[0]
        elif separator is None:
            # „1,234” albo „1.234” bez innych wskazówek: nie zgadujemy.
            return None
        else:
            decimal = separator if marks[0] == separator else None
        normal = ""
        for index, char in enumerate(compact):
            if char in ".,'":
                normal += "." if decimal is not None and index == last else ""
            else:
                normal += char
    normal = normal.replace("−", "-")
    try:
        return float(normal)
    except ValueError:
        return None


def cell_text(page, box):
    """Tekst komórki czytany z jej obszaru na stronie.

    Nie używamy `Table.extract()`: w części wydań PyMuPDF gubi ono spacje
    i przenosi znaki interpunkcyjne do osobnych wierszy.
    """
    if box is None:
        # Komórka scalona z sąsiednią.
        return ""
    left, top, right, bottom = box
    if right - left < 2 or bottom - top < 2:
        return ""
    # Margines chroni przed znakami z sąsiednich komórek.
    area = (left + 0.5, top + 0.5, right - 0.5, bottom - 0.5)
    return clean(page.get_text("text", clip=area))


def join_wrapped(rows):
    """Dokleja do komórki jej dalszy ciąg z następnego wiersza tekstu.

    W tabeli bez linii pionowych każdy wiersz tekstu wychodzi jako osobny
    wiersz tabeli. Wiersz, w którym wypełniona jest jedna komórka z tekstem
    poza pierwszą kolumną, to dalsza część opisu z wiersza wyżej.
    """
    joined = []
    for row in rows:
        filled = [index for index, cell in enumerate(row) if cell]
        column = filled[0] if len(filled) == 1 else 0
        wrapped = (
            joined
            and column > 0
            and column < len(joined[-1])
            and joined[-1][column]
            and joined[-1][0]
            # Sama liczba w wierszu to raczej suma niż dalszy ciąg opisu.
            and not NUMBER.match(CURRENCY.sub("", row[column]).strip())
        )
        if wrapped:
            joined[-1][column] += " " + row[column]
        else:
            joined.append(list(row))
    return joined


def page_tables(page):
    """Tabele na stronie jako listy wierszy z tekstem komórek."""
    result = []
    for strategy in ("lines", "text"):
        try:
            found = page.find_tables(strategy=strategy).tables
        except Exception:  # noqa: BLE001 - strona bez tabel albo nietypowa
            found = []
        for table in found:
            rows = [[cell_text(page, cell) for cell in row.cells] for row in table.rows]
            rows = [row for row in rows if any(row)]
            if len(rows) < 2 or max(len(row) for row in rows) < 2:
                continue
            rows = join_wrapped(rows)
            if strategy == "text":
                cells = sum(len(row) for row in rows)
                filled = sum(1 for row in rows for cell in row if cell)
                if len(rows) < TEXT_MIN_ROWS or filled / cells < TEXT_MIN_FILLED:
                    continue
            result.append({"rows": rows, "top": table.bbox[1], "ruled": strategy == "lines"})
        if result:
            # Tabele z liniami są pewniejsze; układu tekstu szukamy, gdy ich nie ma.
            break
    result.sort(key=lambda item: item["top"])
    return result


def collect(document):
    """Tabele dokumentu; ciąg dalszy tabeli z poprzedniej strony jest doklejany."""
    sheets = []
    # Ostatnia tabela poprzedniej strony: może mieć ciąg dalszy na tej.
    open_table = None
    for index in range(min(document.page_count, MAX_PAGES)):
        page = document[index]
        tables = page_tables(page)
        last = None
        for position, table in enumerate(tables):
            rows = table["rows"]
            width = max(len(row) for row in rows)
            continues = (
                position == 0
                and open_table is not None
                and open_table["width"] == width
                and table["top"] < page.rect.height * CONTINUATION_TOP
            )
            if continues:
                target = open_table["rows"]
                # Nagłówek powtórzony na kolejnej stronie pomijamy.
                target.extend(rows[1:] if rows[0] == target[0] else rows)
                rows = target
            else:
                if len(sheets) >= MAX_SHEETS:
                    return sheets
                sheets.append(rows)
            last = {"rows": rows, "width": width}
        open_table = last
    return sheets


def column_name(index):
    name = ""
    index += 1
    while index:
        index, rest = divmod(index - 1, 26)
        name = chr(65 + rest) + name
    return name


def sheet_xml(rows, separator):
    width = max(len(row) for row in rows)
    widths = [8] * width
    lines = []
    for row_index, row in enumerate(rows, start=1):
        cells = []
        for column, text in enumerate(row):
            if not text:
                continue
            widths[column] = min(60, max(widths[column], len(text) + 2))
            reference = f"{column_name(column)}{row_index}"
            # Pierwszy wiersz to nagłówek: zostaje tekstem, nawet gdy wygląda jak liczba.
            number = None if row_index == 1 else to_number(text, separator)
            style = ' s="1"' if row_index == 1 else ""
            if number is None:
                cells.append(
                    f'<c r="{reference}" t="inlineStr"{style}>'
                    f'<is><t xml:space="preserve">{escape(text)}</t></is></c>'
                )
            else:
                cells.append(f'<c r="{reference}"><v>{number!r}</v></c>')
        lines.append(f'<row r="{row_index}">{"".join(cells)}</row>')
    columns = "".join(
        f'<col min="{index}" max="{index}" width="{value}" customWidth="1"/>'
        for index, value in enumerate(widths, start=1)
    )
    return (
        '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
        '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
        f"<cols>{columns}</cols><sheetData>{''.join(lines)}</sheetData></worksheet>"
    )


STYLES = (
    '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
    '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
    '<fonts count="2"><font><sz val="11"/><name val="Calibri"/></font>'
    '<font><b/><sz val="11"/><name val="Calibri"/></font></fonts>'
    '<fills count="2"><fill><patternFill patternType="none"/></fill>'
    '<fill><patternFill patternType="gray125"/></fill></fills>'
    '<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>'
    '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>'
    '<cellXfs count="2"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>'
    '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/></cellXfs>'
    "</styleSheet>"
)


def write_xlsx(target, sheets):
    cells = [cell for rows in sheets for row in rows[1:] for cell in row if cell]
    separator = decimal_separator(cells)
    numbers = range(1, len(sheets) + 1)
    with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as archive:
        archive.writestr(
            "[Content_Types].xml",
            '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
            '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
            '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
            '<Default Extension="xml" ContentType="application/xml"/>'
            '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>'
            '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>'
            + "".join(
                f'<Override PartName="/xl/worksheets/sheet{number}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>'
                for number in numbers
            )
            + "</Types>",
        )
        archive.writestr(
            "_rels/.rels",
            '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
            '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
            '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>'
            "</Relationships>",
        )
        archive.writestr(
            "xl/workbook.xml",
            '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
            '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
            'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets>'
            + "".join(
                f'<sheet name="{number}" sheetId="{number}" r:id="rId{number}"/>'
                for number in numbers
            )
            + "</sheets></workbook>",
        )
        archive.writestr(
            "xl/_rels/workbook.xml.rels",
            '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
            '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
            + "".join(
                f'<Relationship Id="rId{number}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet{number}.xml"/>'
                for number in numbers
            )
            + f'<Relationship Id="rId{len(sheets) + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>'
            "</Relationships>",
        )
        archive.writestr("xl/styles.xml", STYLES)
        for number, rows in zip(numbers, sheets):
            archive.writestr(f"xl/worksheets/sheet{number}.xml", sheet_xml(rows, separator))


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

    try:
        document = pymupdf.open(source)
    except Exception:
        return 4
    try:
        if document.needs_pass:
            return 3
        if document.page_count == 0:
            return 4
        sheets = collect(document)
    finally:
        document.close()
    if not sheets:
        return 5
    write_xlsx(target, sheets)
    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_xlsx: {type(error).__name__}", file=sys.stderr)
        sys.exit(1)
