from django import template
from django.urls import resolve, Resolver404
from django.utils.safestring import mark_safe

register = template.Library()


@register.simple_tag(takes_context=True)
def social_meta_tags(context):
    """
    Generates appropriate Open Graph and Twitter Card meta tags based on the current page.
    """
    request = context["request"]
    current_url = request.path

    try:
        resolved_view = resolve(current_url)
        view_name = resolved_view.view_name
    except Resolver404:
        view_name = None

    # Default values (used for listing pages)
    title = context.get("self.title", "Servala")
    if hasattr(context.get("self"), "title"):
        title = context["self"].title

    description = context.get(
        "self.meta_description",
        "Servala connects businesses, developers, and cloud service providers on one unique hub",
    )
    image_url = request.build_absolute_uri("/static/img/servala-social-share.png")

    # Customize based on page type
    if view_name == "service_detail" and "service" in context:
        service = context["service"]
        title = f"Servala Managed Service: {service.name}"
        description = (
            f"Managed {service.name} on any cloud provider trusted by Servala."
        )

    elif view_name == "provider_detail" and "provider" in context:
        provider = context["provider"]
        title = f"Servala trusted Cloud Provider: {provider.name}"
        description = f"Managed services on {provider.name} via Servala"

    elif view_name == "partner_detail" and "partner" in context:
        partner = context["partner"]
        title = f"Servala trusted Consulting Partner: {partner.name}"
        description = (
            f"Consulting services from {partner.name} for services available on Servala"
        )

    elif view_name == "offering_detail" and "offering" in context:
        offering = context["offering"]
        title = f"{offering.service.name} on {offering.cloud_provider.name}"
        description = (
            offering.short_description[:160]
            if offering.short_description
            else description
        )

    elif view_name == "services:article_detail" and "article" in context:
        article = context["article"]
        title = f"Servala - {article.title}"
        description = article.excerpt
        # Use article image if available, otherwise default
        if article.image:
            image_url = request.build_absolute_uri(article.image.url)

    # Determine og:type based on view
    og_type = "website"  # default
    if view_name == "services:article_detail" and "article" in context:
        og_type = "article"

    # Generate the HTML for meta tags
    tags = f"""
    <meta property="og:site_name" content="Servala">
    <meta property="og:title" content="{title}">
    <meta property="og:description" content="{description}">
    <meta property="og:type" content="{og_type}">
    <meta property="og:url" content="{request.build_absolute_uri()}">
    <meta property="og:image" content="{image_url}">
    """

    # Add article-specific meta tags if this is an article detail page
    if view_name == "services:article_detail" and "article" in context:
        article = context["article"]

        # Add article-specific Open Graph tags
        article_tags = f"""
    <meta property="article:published_time" content="{article.created_at.isoformat()}">
    <meta property="article:modified_time" content="{article.updated_at.isoformat()}">
    <meta property="article:author" content="{article.author.get_full_name() or article.author.username}">
        """

        # Add article section if related to service, partner, or provider
        if article.related_service:
            article_tags += (
                f'\n    <meta property="article:section" content="Services">'
            )
        elif article.related_consulting_partner:
            article_tags += (
                f'\n    <meta property="article:section" content="Consulting Partners">'
            )
        elif article.related_cloud_provider:
            article_tags += (
                f'\n    <meta property="article:section" content="Cloud Providers">'
            )
        else:
            article_tags += f'\n    <meta property="article:section" content="General">'

        # Add meta keywords as article tags if available
        if article.meta_keywords:
            keywords = [
                keyword.strip()
                for keyword in article.meta_keywords.split(",")
                if keyword.strip()
            ]
            for keyword in keywords:
                article_tags += (
                    f'\n    <meta property="article:tag" content="{keyword}">'
                )

        tags += article_tags

    return mark_safe(tags)
