# Generated by Django 5.2 on 2026-03-09 00:00

import re

from django.db import IntegrityError, migrations
from django.utils.crypto import get_random_string


def _build_base_username(name: str) -> str:
    base_username = (name or "").lower().strip()
    base_username = re.sub(r"\s+", ".", base_username)
    base_username = re.sub(r"[^\w.]", "", base_username)
    if not base_username:
        base_username = "agent"
    return base_username


def _generate_unique_email_address(Endpoint, display_name: str, domain: str) -> str:
    base_username = _build_base_username(display_name)

    email_address = f"{base_username}@{domain}"
    if not Endpoint.objects.filter(channel="email", address__iexact=email_address).exists():
        return email_address

    for index in range(2, 100):
        email_address = f"{base_username}{index}@{domain}"
        if not Endpoint.objects.filter(channel="email", address__iexact=email_address).exists():
            return email_address

    random_suffix = get_random_string(4).lower()
    email_address = f"{base_username}-{random_suffix}@{domain}"
    if not Endpoint.objects.filter(channel="email", address__iexact=email_address).exists():
        return email_address

    raise RuntimeError("Unable to generate a unique email address for alias backfill.")


def backfill_default_agent_email_aliases(apps, schema_editor):
    from django.conf import settings

    domain = (settings.DEFAULT_AGENT_EMAIL_DOMAIN or "").strip().lower()
    if not domain:
        return

    suffix = f"@{domain}"
    Endpoint = apps.get_model("api", "PersistentAgentCommsEndpoint")
    Agent = apps.get_model("api", "PersistentAgent")
    EmailMeta = apps.get_model("api", "PersistentAgentEmailEndpoint")

    owner_agent_ids = (
        Endpoint.objects
        .filter(channel="email", owner_agent_id__isnull=False)
        .values_list("owner_agent_id", flat=True)
        .distinct()
    )

    for agent_id in owner_agent_ids.iterator(chunk_size=500):
        if Endpoint.objects.filter(
            channel="email",
            owner_agent_id=agent_id,
            address__iendswith=suffix,
        ).exists():
            continue

        agent_name = (
            Agent.objects
            .filter(pk=agent_id)
            .values_list("name", flat=True)
            .first()
            or ""
        )
        display_name = (agent_name or "").strip() or "Agent"

        endpoint = None
        for _ in range(3):
            try:
                email_address = _generate_unique_email_address(
                    Endpoint,
                    display_name=display_name,
                    domain=domain,
                )
                endpoint = Endpoint.objects.create(
                    owner_agent_id=agent_id,
                    channel="email",
                    address=email_address.lower(),
                    is_primary=False,
                )
                break
            except IntegrityError:
                continue

        if endpoint is None:
            continue

        EmailMeta.objects.get_or_create(
            endpoint_id=endpoint.id,
            defaults={
                "display_name": display_name,
                "verified": True,
            },
        )


class Migration(migrations.Migration):
    atomic = False

    dependencies = [
        ("api", "0308_llmroutingprofile_summarization_endpoint"),
    ]

    operations = [
        migrations.RunPython(
            backfill_default_agent_email_aliases,
            reverse_code=migrations.RunPython.noop,
            atomic=False,
        ),
    ]
