# Copyright (C) 2026 NPO NT
# SPDX-License-Identifier: AGPL-3.0-only

from __future__ import annotations

import io
from pathlib import Path
from typing import Iterable

import pymupdf as fitz
from PIL import ImageDraw

from . import __version__
from .models import Box, DocumentData, Finding


REDACTION_FILL = (19, 33, 27)
REDACTION_MARGIN = 6


class SanitizationError(RuntimeError):
    pass


def _page_boxes(findings: Iterable[Finding], page_index: int) -> list[Box]:
    return [finding.box for finding in findings if finding.page_index == page_index and finding.selected]


def build_raster_pdf(document: DocumentData, findings: Iterable[Finding], output_path: str | Path) -> None:
    """Build a fresh raster-only PDF without copying source PDF objects or metadata."""

    target = Path(output_path)
    if target.exists():
        raise SanitizationError("Выходной файл уже существует; перезапись запрещена")
    target.parent.mkdir(parents=True, exist_ok=True)
    selected = list(findings)
    output = fitz.open()
    try:
        for page in document.pages:
            image = page.image.convert("RGB").copy()
            draw = ImageDraw.Draw(image)
            for box in _page_boxes(selected, page.index):
                expanded = box.expand(REDACTION_MARGIN, page.width, page.height).normalized()
                draw.rectangle((expanded.x0, expanded.y0, expanded.x1, expanded.y1), fill=REDACTION_FILL)
            image_buffer = io.BytesIO()
            image.save(image_buffer, format="PNG", optimize=True)
            output_page = output.new_page(width=page.width_points, height=page.height_points)
            output_page.insert_image(output_page.rect, stream=image_buffer.getvalue(), keep_proportion=False)
        output.set_metadata(
            {
                "title": "MIKA cleaned navigation copy",
                "author": "",
                "subject": "Locally de-identified review copy",
                "keywords": "",
                "creator": "MIKA De-ID Local",
                "producer": f"MIKA De-ID Local {__version__}",
                "creationDate": "",
                "modDate": "",
            }
        )
        output.save(target, garbage=4, clean=True, deflate=True, incremental=False, encryption=fitz.PDF_ENCRYPT_NONE)
    except Exception:
        if target.exists():
            target.unlink()
        raise
    finally:
        output.close()
