# Generated by Django 5.2 on 2025-11-19 19:02

import django.core.validators
from decimal import Decimal
from django.db import migrations, models
from constants.plans import PlanNames


def set_default_llm_tiers(apps, schema_editor):
    PersistentAgent = apps.get_model('api', 'PersistentAgent')
    UserBilling = apps.get_model('api', 'UserBilling')

    PersistentAgent.objects.filter(organization__isnull=False).update(preferred_llm_tier='premium')

    paid_user_ids = UserBilling.objects.exclude(subscription=PlanNames.FREE).values_list('user_id', flat=True)
    PersistentAgent.objects.filter(organization__isnull=True, user_id__in=paid_user_ids).update(preferred_llm_tier='premium')


def reset_llm_tiers(apps, schema_editor):
    PersistentAgent = apps.get_model('api', 'PersistentAgent')
    PersistentAgent.objects.update(preferred_llm_tier='standard')


def seed_max_multipliers(apps, schema_editor):
    PersistentLLMTier = apps.get_model('api', 'PersistentLLMTier')
    PersistentLLMTier.objects.filter(is_max=True).update(credit_multiplier=Decimal('5.00'))
    PersistentLLMTier.objects.filter(is_premium=True).update(credit_multiplier=Decimal('2.00'))


def reset_max_multipliers(apps, schema_editor):
    PersistentLLMTier = apps.get_model('api', 'PersistentLLMTier')
    PersistentLLMTier.objects.update(credit_multiplier=Decimal('1.00'))


class Migration(migrations.Migration):

    dependencies = [
        ('api', '0198_add_browser_supports_temperature'),
    ]

    operations = [
        migrations.AddField(
            model_name='persistentagent',
            name='preferred_llm_tier',
            field=models.CharField(choices=[('standard', 'Standard'), ('premium', 'Premium'), ('max', 'Max')], default='standard', help_text='Preferred intelligence tier controlling LLM routing for this agent.', max_length=16),
        ),
        migrations.AddField(
            model_name='persistentllmtier',
            name='credit_multiplier',
            field=models.DecimalField(decimal_places=2, default=Decimal('1.00'), help_text='Multiplier applied to credit consumption for this tier.', max_digits=6, validators=[django.core.validators.MinValueValidator(Decimal('0.01'))]),
        ),
        migrations.RunPython(set_default_llm_tiers, reset_llm_tiers),
        migrations.RunPython(seed_max_multipliers, reset_max_multipliers),
    ]
