"""PDF watermarking for restricted document downloads (PRD REPO-SP4)."""

from __future__ import annotations

import io
import logging

logger = logging.getLogger(__name__)


def apply_watermark(pdf_bytes: bytes, *, user_full_name: str, timestamp: str) -> bytes:
    """Overlay a translucent diagonal watermark on each page of a PDF.

    Returns the original bytes unchanged if reportlab/pypdf are unavailable
    or if the input is not a valid PDF — the caller still gets a usable file.
    """
    try:
        from pypdf import PdfReader, PdfWriter
        from reportlab.lib.pagesizes import letter
        from reportlab.lib.units import inch
        from reportlab.pdfgen import canvas
    except ImportError:
        logger.warning("watermark dependencies missing; serving file unchanged")
        return pdf_bytes

    try:
        reader = PdfReader(io.BytesIO(pdf_bytes))
    except Exception:  # pragma: no cover — invalid pdf
        logger.warning("watermark: input not a valid PDF; serving unchanged")
        return pdf_bytes

    writer = PdfWriter()

    for page in reader.pages:
        width = float(page.mediabox.width)
        height = float(page.mediabox.height)

        overlay_buf = io.BytesIO()
        c = canvas.Canvas(overlay_buf, pagesize=(width, height))
        c.saveState()
        c.translate(width / 2, height / 2)
        c.rotate(35)
        c.setFont("Helvetica-Bold", 32)
        c.setFillGray(0.85, 0.35)
        c.drawCentredString(0, 30, user_full_name[:80] or "Authorised user")
        c.setFont("Helvetica", 14)
        c.drawCentredString(0, -10, timestamp)
        c.restoreState()
        c.showPage()
        c.save()

        overlay_buf.seek(0)
        overlay_reader = PdfReader(overlay_buf)
        page.merge_page(overlay_reader.pages[0])
        writer.add_page(page)

    out_buf = io.BytesIO()
    writer.write(out_buf)
    return out_buf.getvalue()


def apply_docx_watermark(docx_bytes: bytes, *, user_full_name: str, timestamp: str) -> bytes:
    """Stamp a restricted-download notice on every section footer of a DOCX
    (PRD REPO-SP4 FRREP-AC007).

    A true diagonal image watermark requires raw OOXML shape manipulation that
    python-docx doesn't expose; a footer notice is the mechanism python-docx
    *does* support and carries the same evidentiary value (who downloaded it,
    when) that the PDF watermark provides. Returns the original bytes
    unchanged if python-docx is unavailable or the input isn't a valid DOCX.
    """
    try:
        from docx import Document as DocxDocument
        from docx.enum.text import WD_ALIGN_PARAGRAPH
        from docx.shared import Pt, RGBColor
    except ImportError:
        logger.warning("watermark dependencies missing; serving docx unchanged")
        return docx_bytes

    try:
        doc = DocxDocument(io.BytesIO(docx_bytes))
    except Exception:  # pragma: no cover — invalid docx
        logger.warning("watermark: input not a valid DOCX; serving unchanged")
        return docx_bytes

    notice = (
        f"Downloaded by {(user_full_name or 'Authorised user')[:80]} · {timestamp} "
        "· Restricted document — do not redistribute."
    )
    for section in doc.sections:
        footer = section.footer
        footer.is_linked_to_previous = False
        paragraph = footer.paragraphs[0] if footer.paragraphs else footer.add_paragraph()
        paragraph.text = notice
        paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
        for run in paragraph.runs:
            run.italic = True
            run.font.size = Pt(8)
            run.font.color.rgb = RGBColor(0x99, 0x99, 0x99)

    out_buf = io.BytesIO()
    doc.save(out_buf)
    return out_buf.getvalue()
