# Generated by Django 5.2 on 2025-02-17
from django.db import migrations


OPENROUTER_PREFIX = "openrouter/"
OPENROUTER_BASE = "https://openrouter.ai/api/v1"


def _fix_openrouter_browser_models(apps, schema_editor):
    BrowserModelEndpoint = apps.get_model("api", "BrowserModelEndpoint")
    PersistentModelEndpoint = apps.get_model("api", "PersistentModelEndpoint")
    LLMProvider = apps.get_model("api", "LLMProvider")

    provider = LLMProvider.objects.filter(key="openrouter").first()
    if not provider:
        return
    if not provider.model_prefix:
        provider.model_prefix = OPENROUTER_PREFIX
        provider.save(update_fields=["model_prefix"])

    # Browser endpoints: strip provider prefix and ensure base URL
    for endpoint in BrowserModelEndpoint.objects.filter(provider=provider):
        changed_fields = []
        model = (endpoint.browser_model or "").strip()

        if model.startswith(OPENROUTER_PREFIX):
            endpoint.browser_model = model[len(OPENROUTER_PREFIX):]
            changed_fields.append("browser_model")

        if not endpoint.browser_base_url:
            endpoint.browser_base_url = OPENROUTER_BASE
            changed_fields.append("browser_base_url")

        if changed_fields:
            endpoint.save(update_fields=changed_fields)

    # Persistent endpoints: strip provider prefix (api_base stays untouched)
    for endpoint in PersistentModelEndpoint.objects.filter(provider=provider):
        model = (endpoint.litellm_model or "").strip()
        if model.startswith(OPENROUTER_PREFIX):
            endpoint.litellm_model = model[len(OPENROUTER_PREFIX):]
            endpoint.save(update_fields=["litellm_model"])


class Migration(migrations.Migration):

    dependencies = [
        ("api", "0194_promptconfig_enabled_tool_limits"),
    ]

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