"""Generate User Agreement acceptance PDF (user details + body + signature)."""

from __future__ import annotations

import io
import re
from html import unescape

from django.core.files.base import ContentFile


def _strip_html(html: str) -> str:
    text = unescape(html or '')
    text = re.sub(r'(?i)<br\s*/?>', '\n', text)
    text = re.sub(r'(?i)</p\s*>', '\n\n', text)
    text = re.sub(r'(?i)</h[1-6]\s*>', '\n\n', text)
    text = re.sub(r'<[^>]+>', '', text)
    text = re.sub(r'\n{3,}', '\n\n', text)
    return text.strip()


def agreement_title_for_pdf(acceptance) -> str:
    title = (getattr(acceptance, 'agreement_title_snapshot', '') or '').strip()
    if title:
        return title
    doc = getattr(acceptance, 'agreement_document', None)
    return (doc.title if doc else '') or 'User Agreement'


def agreement_text_for_pdf(acceptance) -> str:
    """Prefer stored app snapshot; fall back to CMS body for legacy rows."""
    snapshot = (getattr(acceptance, 'agreement_text_snapshot', '') or '').strip()
    if snapshot:
        return snapshot
    doc = getattr(acceptance, 'agreement_document', None)
    return _strip_html(doc.body if doc else '')


def build_agreement_acceptance_pdf_bytes(acceptance) -> bytes:
    from reportlab.lib.pagesizes import A4
    from reportlab.lib.units import mm
    from reportlab.lib.utils import ImageReader
    from reportlab.pdfgen import canvas

    buf = io.BytesIO()
    c = canvas.Canvas(buf, pagesize=A4)
    width, height = A4
    margin = 18 * mm
    y = height - margin

    def draw_line(text, size=11, leading=14, bold=False):
        nonlocal y
        if y < margin + 20:
            c.showPage()
            y = height - margin
        c.setFont('Helvetica-Bold' if bold else 'Helvetica', size)
        c.drawString(margin, y, text[:110])
        y -= leading

    title = agreement_title_for_pdf(acceptance)
    body = agreement_text_for_pdf(acceptance)

    draw_line('Truck Me — User Agreement Acceptance', size=14, leading=18, bold=True)
    draw_line(f'Document: {title}', size=10, leading=14)
    y -= 6
    draw_line('User details', size=12, leading=16, bold=True)
    draw_line(f'User ID: {acceptance.user_id}')
    draw_line(f'Full name: {acceptance.full_name_at_accept or "—"}')
    draw_line(f'Email: {acceptance.email_at_accept or "—"}')
    draw_line(f'Phone: {acceptance.phone_at_accept or "—"}')
    draw_line(f'Account type: {acceptance.account_type_at_accept or "—"}')
    draw_line(f'Accepted at: {acceptance.accepted_at.isoformat() if acceptance.accepted_at else "—"}')
    if acceptance.ip_address:
        draw_line(f'IP: {acceptance.ip_address}')
    if acceptance.user_agent:
        draw_line(f'User agent: {acceptance.user_agent[:100]}')
    y -= 8
    draw_line('Agreement text', size=12, leading=16, bold=True)
    c.setFont('Helvetica', 9)
    max_width = width - 2 * margin
    for paragraph in body.split('\n'):
        paragraph = paragraph.strip()
        if not paragraph:
            y -= 8
            continue
        words = paragraph.split()
        line = ''
        for word in words:
            trial = f'{line} {word}'.strip()
            if c.stringWidth(trial, 'Helvetica', 9) <= max_width:
                line = trial
            else:
                if y < margin + 20:
                    c.showPage()
                    y = height - margin
                    c.setFont('Helvetica', 9)
                c.drawString(margin, y, line)
                y -= 12
                line = word
        if line:
            if y < margin + 20:
                c.showPage()
                y = height - margin
                c.setFont('Helvetica', 9)
            c.drawString(margin, y, line)
            y -= 12

    y -= 12
    if y < margin + 60:
        c.showPage()
        y = height - margin
    c.setFont('Helvetica-Bold', 12)
    c.drawString(margin, y, 'Signature')
    y -= 10

    if acceptance.signature_file:
        try:
            acceptance.signature_file.open('rb')
            img = ImageReader(acceptance.signature_file)
            acceptance.signature_file.close()
            img_w, img_h = 70 * mm, 30 * mm
            if y - img_h < margin:
                c.showPage()
                y = height - margin
            c.drawImage(
                img,
                margin,
                y - img_h,
                width=img_w,
                height=img_h,
                preserveAspectRatio=True,
                mask='auto',
            )
            y -= img_h + 8
        except Exception:
            c.setFont('Helvetica', 10)
            c.drawString(margin, y, '(Signature on file — could not embed image)')
    else:
        c.setFont('Helvetica', 10)
        c.drawString(margin, y, '(No signature file)')

    c.showPage()
    c.save()
    return buf.getvalue()


def save_acceptance_pdf(acceptance) -> None:
    pdf_bytes = build_agreement_acceptance_pdf_bytes(acceptance)
    filename = f'agreement_user{acceptance.user_id}.pdf'
    acceptance.pdf_file.save(filename, ContentFile(pdf_bytes), save=True)
