# Generated by GPT-5.2-Codex-Max on 2025-02-14

from __future__ import annotations

import json
from pathlib import Path

from django.db import migrations


FIXTURE_GLOB = "sigil_roots__*.json"


def _iter_fixture_entries(fixtures_dir: Path):
    for path in sorted(fixtures_dir.glob(FIXTURE_GLOB)):
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
        except Exception:
            continue
        if not isinstance(data, list):
            continue
        for entry in data:
            if not isinstance(entry, dict):
                continue
            fields = entry.get("fields") or {}
            if not isinstance(fields, dict):
                continue
            yield fields


def seed_sigil_roots(apps, schema_editor):
    del schema_editor

    SigilRoot = apps.get_model("sigils", "SigilRoot")
    ContentType = apps.get_model("contenttypes", "ContentType")
    manager = getattr(SigilRoot, "all_objects", SigilRoot._base_manager)

    if manager.exists():
        return

    fixtures_dir = Path(__file__).resolve().parent.parent / "fixtures"

    for fields in _iter_fixture_entries(fixtures_dir):
        prefix = fields.get("prefix")
        context_type = fields.get("context_type")
        if not prefix or not context_type:
            continue

        content_type = fields.get("content_type")
        ct_obj = None
        if isinstance(content_type, (list, tuple)) and len(content_type) == 2:
            app_label, model_name = content_type
            try:
                ct_obj = ContentType.objects.get_by_natural_key(app_label, model_name)
            except ContentType.DoesNotExist:
                continue

        manager.update_or_create(
            prefix=prefix,
            defaults={
                "context_type": context_type,
                "content_type": ct_obj,
                "is_seed_data": bool(fields.get("is_seed_data", False)),
                "is_deleted": bool(fields.get("is_deleted", False)),
            },
        )


class Migration(migrations.Migration):

    dependencies = [
        ("contenttypes", "0002_remove_content_type_name"),
        ("sigils", "0002_alter_sigilroot_context_type"),
    ]

    operations = [
        migrations.RunPython(seed_sigil_roots, migrations.RunPython.noop),
    ]
