# Generated by Django 5.2 on 2025-11-05 00:00

from django.db import migrations, models


RAW_AGENT_COLOR_PALETTE = [
    "#0074d4",
    "#705fe3",
    "#b35e90",
    "#90a7dc",
    "#ca4166",
    "#d7a31a",
    "#c05200",
    "#008d90",
    "#008a47",
    "#ff7999",
    "#414656",
    "#ffeecb",
    "#a5abbd",
    "#8ced85",
    "#e3f0ff",
    "#877555",
]


def _seed_agent_colors(apps, schema_editor):
    AgentColor = apps.get_model("api", "AgentColor")
    PersistentAgent = apps.get_model("api", "PersistentAgent")

    seen = set()
    palette = []
    for hex_value in RAW_AGENT_COLOR_PALETTE:
        normalized = hex_value.strip().lower()
        if normalized in seen:
            continue
        seen.add(normalized)
        palette.append(normalized.upper())

    if not palette:
        palette = ["#0074D4"]

    colors = []
    for index, hex_value in enumerate(palette):
        color, _ = AgentColor.objects.update_or_create(
            name=f"color_{index + 1}",
            defaults={
                "hex_value": hex_value,
                "sort_order": index,
                "is_active": True,
            },
        )
        colors.append(color)

    if not colors:
        return

    color_ids = [color.id for color in colors]
    palette_size = len(color_ids)

    def assign_queryset(qs, owner_field):
        grouped = {}
        for agent in qs.order_by(owner_field, "created_at", "id"):
            owner_id = getattr(agent, owner_field)
            if owner_id is None:
                continue
            grouped.setdefault(owner_id, []).append(agent)

        for owner_id, agents in grouped.items():
            for index, agent in enumerate(agents):
                color_id = color_ids[index % palette_size]
                PersistentAgent.objects.filter(pk=agent.pk).update(agent_color_id=color_id)

    personal_agents = PersistentAgent.objects.filter(organization__isnull=True, agent_color__isnull=True)
    assign_queryset(personal_agents, "user_id")

    org_agents = PersistentAgent.objects.filter(organization__isnull=False, agent_color__isnull=True)
    assign_queryset(org_agents, "organization_id")


class Migration(migrations.Migration):

    dependencies = [
        ('api', '0175_persistentagent_tags_and_more'),
    ]

    operations = [
        migrations.CreateModel(
            name='AgentColor',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=64, unique=True)),
                ('hex_value', models.CharField(max_length=7, unique=True)),
                ('sort_order', models.PositiveIntegerField(default=0)),
                ('is_active', models.BooleanField(default=True)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
            ],
            options={
                'ordering': ['sort_order', 'id'],
            },
        ),
        migrations.AddField(
            model_name='persistentagent',
            name='agent_color',
            field=models.ForeignKey(blank=True, help_text='UI accent color assigned to this agent.', null=True, on_delete=models.deletion.SET_NULL, related_name='persistent_agents', to='api.agentcolor'),
        ),
        migrations.RunPython(_seed_agent_colors, migrations.RunPython.noop),
    ]
