"""Shared helpers for disseminations link tracking."""
from urllib.parse import urlencode, urlparse, parse_qsl, urlunparse

from django.conf import settings
from django.utils.text import slugify

from apps.tools.models import URL


def short_link_url(short_code: str) -> str:
    """Absolute, shareable short link for a code. Resolves to the public redirect."""
    if not short_code:
        return ""
    base = getattr(settings, "SHORTLINK_BASE_URL", "").rstrip("/")
    return f"{base}/api/urls/{short_code}/"


def post_attribution_id(post) -> str:
    """Canonical, dashless id used as utm_content for downstream attribution.

    UUIDField renders dashless in-memory but dashed after a DB load; normalize
    so the value written into the link matches the value queried later.
    """
    return str(post.id).replace("-", "")


def _utm_url(base: str, *, source: str, campaign: str, content: str) -> str:
    """Append UTM params to a URL, preserving any author-supplied ones."""
    parts = urlparse(base)
    q = dict(parse_qsl(parts.query))
    q.setdefault("utm_source", source or "social")
    q.setdefault("utm_medium", "social")
    if campaign:
        q.setdefault("utm_campaign", campaign)
    if content:
        q.setdefault("utm_content", content)
    return urlunparse(parts._replace(query=urlencode(q)))


def ensure_tracking_link(post, user=None):
    """Create or refresh the post's tracked short link. Idempotent.

    Re-generating updates the destination (re-applies UTM) but keeps the
    existing short_code and accumulated clicks/AccessLogs. Returns the URL
    instance, or None when the post has no link_url.
    """
    if not post.link_url:
        return None
    source = post.channels.first().platform if post.channels.exists() else "social"
    campaign = slugify(post.campaign.name) if post.campaign else ""
    target = _utm_url(post.link_url, source=source, campaign=campaign, content=post_attribution_id(post))
    if post.tracking_url:
        post.tracking_url.original_url = target
        post.tracking_url.save(update_fields=["original_url", "updated_at"])
    else:
        post.tracking_url = URL.objects.create(
            original_url=target,
            title=(post.title or "")[:255],
            created_by=user if (user and user.is_authenticated) else None,
        )
        post.save(update_fields=["tracking_url", "updated_at"])
    return post.tracking_url
