# Generated by Django 5.2 on 2025-07-26 21:27

from django.db import migrations, models
from django.db.models import Count


# ---------------------------------------------------------------------------
# Utility: make existing PersistentAgentSecret.name values unique per
# (agent, domain_pattern) so the new UniqueConstraint can be created without
# failing.  When duplicates are found we append “ (2)”, “ (3)”, etc.
# ---------------------------------------------------------------------------


def _deduplicate_secret_names(apps, schema_editor):
    Secret = apps.get_model("api", "PersistentAgentSecret")

    # Identify duplicate (agent, domain_pattern, name) combos.
    dupes = (
        Secret.objects
        .values("agent", "domain_pattern", "name")
        .annotate(c=Count("id"))
        .filter(c__gt=1)
    )

    for entry in dupes:
        agent_id = entry["agent"]
        domain = entry["domain_pattern"]
        base_name = entry["name"]

        # Gather the secrets in a deterministic order so that we keep the first
        # one unchanged and rename the rest.
        secrets = (
            Secret.objects
            .filter(agent_id=agent_id, domain_pattern=domain, name=base_name)
            .order_by("created_at", "id")
        )

        # Skip the first (it can keep the original name).
        for idx, secret in enumerate(secrets[1:], start=2):
            # Find the first available "{base_name} (n)" not already used.
            suffix = idx
            while True:
                candidate = f"{base_name} ({suffix})"[:128]
                # Check against existing names for this agent+domain.
                exists = Secret.objects.filter(
                    agent_id=agent_id,
                    domain_pattern=domain,
                    name=candidate,
                ).exists()
                if not exists:
                    break
                suffix += 1

            secret.name = candidate
            secret.save(update_fields=["name"])


class Migration(migrations.Migration):

    dependencies = [
        ('api', '0068b_populate_secret_names'),
    ]

    operations = [
        # Ensure there are no duplicate names per (agent, domain_pattern) before we add
        # the unique constraint.  We suffix duplicates with “ (n)” where n starts at 2.
        migrations.RunPython(
            _deduplicate_secret_names,
            migrations.RunPython.noop,
        ),
        migrations.AlterModelOptions(
            name='persistentagentsecret',
            options={'ordering': ['domain_pattern', 'name']},
        ),
        migrations.AddField(
            model_name='persistentagentsecret',
            name='description',
            field=models.TextField(blank=True, help_text='Optional description of what this secret is used for'),
        ),
        migrations.AlterField(
            model_name='persistentagentsecret',
            name='name',
            field=models.CharField(
                max_length=128,
                default='Unnamed Secret',
                help_text="Human-readable name for this secret (e.g., 'X Password', 'API Key')",
            ),
        ),
        migrations.AlterField(
            model_name='persistentagentsecret',
            name='key',
            field=models.CharField(help_text='Secret key name (auto-generated from name, alphanumeric with underscores only)', max_length=64),
        ),
        migrations.AddConstraint(
            model_name='persistentagentsecret',
            constraint=models.UniqueConstraint(fields=('agent', 'domain_pattern', 'name'), name='unique_agent_domain_secret_name'),
        ),
    ]
