# Generated by Plain 0.68.0 on 2025-09-25 19:32

from typing import Any

from plain import models
from plain.models import migrations


def extract_tracking_params_migration(url: str) -> tuple[str, str, str]:
    """
    Extract tracking parameters from a URL for migration purposes.
    This is a copy of the logic from params.py to avoid import dependencies.
    """
    from urllib.parse import parse_qs, urlparse

    parsed = urlparse(url)
    params = parse_qs(parsed.query)

    source = ""
    medium = ""
    campaign = ""

    # Extract source (priority order)
    if utm_source := params.get("utm_source", [""])[0]:
        source = utm_source.strip().lower()
    elif ref := params.get("ref", [""])[0]:
        source = ref.strip().lower()
    elif "gclid" in params:
        source = "google"
    elif "fbclid" in params:
        source = "facebook"
    elif "msclkid" in params:
        source = "bing"
    elif "ttclid" in params:
        source = "tiktok"
    elif "twclid" in params:
        source = "twitter"

    # Extract medium
    if utm_medium := params.get("utm_medium", [""])[0]:
        medium = utm_medium.strip().lower()
    elif "gclid" in params:
        medium = "cpc"
    elif "fbclid" in params:
        medium = "social"
    elif "msclkid" in params:
        medium = "cpc"
    elif "ttclid" in params:
        medium = "cpc"
    elif "twclid" in params:
        medium = "cpc"

    # Extract campaign
    if utm_campaign := params.get("utm_campaign", [""])[0]:
        campaign = utm_campaign.strip().lower()

    return source, medium, campaign


def populate_attribution_fields(apps: Any, schema_editor: Any) -> None:
    """
    Populate source, medium, campaign fields for existing pageviews
    that have tracking parameters in their URLs.
    """
    Pageview = apps.get_model("plainpageviews", "pageview")

    # Find pageviews that have utm_source parameters
    pageviews = Pageview.query.filter(url__icontains="utm_source=")

    for pageview in pageviews:
        try:
            source, medium, campaign = extract_tracking_params_migration(pageview.url)

            if source or medium or campaign:
                pageview.source = source
                pageview.medium = medium
                pageview.campaign = campaign
                pageview.save(update_fields=["source", "medium", "campaign"])
        except Exception:
            # Skip any URLs that can't be parsed
            continue


class Migration(migrations.Migration):
    dependencies = [
        (
            "plainpageviews",
            "0002_remove_pageview_plainpagevi_session_5545cf_idx_and_more",
        ),
    ]

    operations = [
        migrations.AddField(
            model_name="pageview",
            name="campaign",
            field=models.CharField(max_length=200, required=False),
        ),
        migrations.AddField(
            model_name="pageview",
            name="medium",
            field=models.CharField(max_length=200, required=False),
        ),
        migrations.AddField(
            model_name="pageview",
            name="source",
            field=models.CharField(max_length=200, required=False),
        ),
        migrations.AddIndex(
            model_name="pageview",
            index=models.Index(fields=["source"], name="plainpagevi_source_23e80d_idx"),
        ),
        migrations.AddIndex(
            model_name="pageview",
            index=models.Index(fields=["medium"], name="plainpagevi_medium_370c1b_idx"),
        ),
        migrations.RunPython(
            populate_attribution_fields,
        ),
    ]
