"""Retire the legacy primary/secondary file pair in favour of collections.

The old sites let a document carry a second file — a leftover from an earlier
generation of the site, where minutes and financials were pinned together. It
stopped making sense once documents started arriving in larger batches. Each
secondary file becomes a document in its own right, and the pair is placed in a
collection so the relationship survives.
"""
import os
import re

from django.db import migrations
from django.utils.text import slugify


def _title_from_filename(path, fallback):
    stem = os.path.splitext(os.path.basename(path or ""))[0]
    stem = re.sub(r"[-_]+", " ", stem)
    stem = re.sub(r"\s+", " ", stem).strip()
    # Importer filenames can be opaque; fall back when nothing readable is left.
    if len(stem) < 4 or not re.search(r"[A-Za-z]{3}", stem):
        return fallback
    return stem[:255].title()


def split_secondary(apps, schema_editor):
    Document = apps.get_model("documents", "Document")
    Collection = apps.get_model("documents", "Collection")

    used_slugs = set(Collection.objects.values_list("slug", flat=True))

    for document in Document.objects.exclude(secondary_file="").exclude(secondary_file=None):
        base_slug = slugify(document.title)[:200] or f"collection-{document.pk}"
        slug = base_slug
        suffix = 2
        while slug in used_slugs:
            slug = f"{base_slug}-{suffix}"
            suffix += 1
        used_slugs.add(slug)

        collection = Collection.objects.create(
            title=document.title[:200],
            slug=slug,
            category_id=document.category_id,
            summary=document.summary or "",
            occurred_on=document.published_date,
        )

        Document.objects.create(
            title=_title_from_filename(document.secondary_file.name,
                                       f"{document.title} (2)")[:255],
            collection=collection,
            category_id=document.category_id,
            summary="",
            file=document.secondary_file.name,
            published=document.published,
            published_date=document.published_date,
            uploaded_by_id=document.uploaded_by_id,
        )

        document.collection = collection
        document.secondary_file = None
        document.save(update_fields=["collection", "secondary_file"])


def noop(apps, schema_editor):
    """Irreversible by design: the split documents are real records now."""


class Migration(migrations.Migration):
    dependencies = [("documents", "0004_tag_collection_document_collection_document_tags")]
    operations = [migrations.RunPython(split_secondary, noop)]
