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
        )

    # 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="website">
    <meta property="og:url" content="{request.build_absolute_uri()}">
    <meta property="og:image" content="{image_url}">
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="{title}">
    <meta name="twitter:description" content="{description}">
    <meta name="twitter:image" content="{image_url}">
    """

    return mark_safe(tags)
