"""Data migration — populate StrategicObjective rows + M2M links from the
legacy `FundingRecord.strategic_objectives` TextField.

PRD §5.1 FRFA-GPS006. The TextField is preserved (see 0020) so legacy UIs
keep rendering; new writes should go through `strategic_objective_refs`.
"""
from __future__ import annotations

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

# Inlined from apps.rims.grants.services.split_strategic_objectives to avoid
# importing the live services module from a historical migration.
def _split_objectives(raw: str) -> list[str]:
    import re as _re

    if not raw:
        return []
    parts = _re.split(r"[,;\n]+", raw)
    seen: set[str] = set()
    ordered: list[str] = []
    for p in parts:
        clean = p.strip()
        if not clean:
            continue
        key = clean.lower()
        if key in seen:
            continue
        seen.add(key)
        ordered.append(clean)
    return ordered


def forwards(apps, schema_editor):
    FundingRecord = apps.get_model("rims_grants", "FundingRecord")
    StrategicObjective = apps.get_model("rims_grants", "StrategicObjective")

    for fr in FundingRecord.objects.exclude(strategic_objectives="").iterator():
        names = _split_objectives(fr.strategic_objectives or "")
        for name in names:
            # StrategicObjective.name is CharField(max_length=255); truncate
            # defensively in case the legacy TextField contained a paragraph.
            short_name = name[:255]
            slug = slugify(short_name)[:120] or f"obj-{fr.pk}"
            obj, _ = StrategicObjective.objects.get_or_create(
                slug=slug, defaults={"name": short_name, "active": True}
            )
            fr.strategic_objective_refs.add(obj)


def backwards(apps, schema_editor):
    # No-op — the legacy TextField is preserved, so reversing the data
    # migration simply orphans the created StrategicObjective rows (they may
    # be reused by other records).
    pass


class Migration(migrations.Migration):
    dependencies = [
        ("rims_grants", "0020_strategicobjective_and_more"),
    ]
    operations = [migrations.RunPython(forwards, backwards)]
