# Persist app-posted agreement text snapshot on acceptances

import hashlib
import re
from html import unescape

from django.db import migrations, models


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 backfill_agreement_text_snapshots(apps, schema_editor):
    UserAgreementAcceptance = apps.get_model('accounts', 'UserAgreementAcceptance')
    for row in UserAgreementAcceptance.objects.select_related('agreement_document').all():
        if (row.agreement_text_snapshot or '').strip():
            continue
        doc = row.agreement_document
        text = _strip_html(getattr(doc, 'body', '') or '')
        title = (getattr(doc, 'title', '') or '')[:255]
        digest = hashlib.sha256(text.encode('utf-8')).hexdigest() if text else ''
        UserAgreementAcceptance.objects.filter(pk=row.pk).update(
            agreement_text_snapshot=text,
            agreement_title_snapshot=title,
            agreement_text_hash=digest,
        )


class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0038_user_agreements_permission'),
    ]

    operations = [
        migrations.AddField(
            model_name='useragreementacceptance',
            name='agreement_text_snapshot',
            field=models.TextField(
                blank=True,
                default='',
                help_text='Exact agreement text the client posted at accept time.',
            ),
        ),
        migrations.AddField(
            model_name='useragreementacceptance',
            name='agreement_title_snapshot',
            field=models.CharField(blank=True, default='', max_length=255),
        ),
        migrations.AddField(
            model_name='useragreementacceptance',
            name='agreement_text_hash',
            field=models.CharField(
                blank=True,
                default='',
                help_text='SHA-256 hex digest of agreement_text_snapshot.',
                max_length=64,
            ),
        ),
        migrations.RunPython(backfill_agreement_text_snapshots, migrations.RunPython.noop),
    ]
