# hub/services/templatetags/json_ld_tags.py
from django import template
from django.urls import resolve, Resolver404
from django.utils.safestring import mark_safe
import json

register = template.Library()


@register.simple_tag(takes_context=True)
def json_ld_structured_data(context):
    """
    Generates appropriate JSON-LD structured data based on the current page.
    For schemas, see https://schema.org/
    """
    request = context.get("request")
    if not request:
        return ""

    current_url = request.path
    base_url = f"{request.scheme}://{request.get_host()}"

    # Default organization data (for Servala)
    organization_data = {
        "@context": "https://schema.org",
        "@type": "Organization",
        "name": "Servala",
        "url": base_url,
        "logo": f"{base_url}/static/img/header-logo.png",
        "contactPoint": {
            "@type": "ContactPoint",
            "telephone": "+41 44 545 53 00",
            "email": "hi@servala.com",
            "contactType": "Sales",
        },
        "address": {
            "@type": "PostalAddress",
            "streetAddress": "Neugasse 10",
            "addressLocality": "Zurich",
            "postalCode": "8005",
            "addressCountry": "CH",
        },
    }

    # Add try-except around the view resolution
    try:
        resolved_view = resolve(current_url)
        view_name = resolved_view.url_name
    except Resolver404:
        # For 404 pages or other unresolvable URLs, return minimal data
        data = {
            "@context": "https://schema.org",
            "@type": "WebSite",
            "name": "Servala - Open Cloud Native Service Hub",
            "url": base_url,
        }
        json_ld = json.dumps(data, indent=2)
        return mark_safe(f'<script type="application/ld+json">{json_ld}</script>')

    # Handle different page types
    if view_name == "homepage":
        data = [
            {
                "@context": "https://schema.org",
                "@type": "WebSite",
                "name": "Servala - Open Cloud Native Service Hub",
                "url": base_url,
                "description": "Servala connects businesses, developers, and cloud service providers on one unique hub with secure, scalable, and easy-to-use cloud-native services.",
                "potentialAction": {
                    "@type": "SearchAction",
                    "target": f"{base_url}/service/?search={{search_term_string}}",
                    "query-input": "required name=search_term_string",
                },
            },
            organization_data,
        ]

    elif view_name == "service_list":
        data = {
            "@context": "https://schema.org",
            "@type": "CollectionPage",
            "name": "Cloud Services - Servala",
            "url": f"{base_url}/service/",
            "description": "Explore all available cloud services on Servala, with new services added regularly.",
            "isPartOf": {"@type": "WebSite", "name": "Servala", "url": base_url},
        }

    elif view_name == "provider_list":
        data = {
            "@context": "https://schema.org",
            "@type": "CollectionPage",
            "name": "Cloud Providers - Servala",
            "url": f"{base_url}/providers/",
            "description": "Discover cloud providers on Servala offering reliable infrastructure and innovative cloud computing solutions.",
            "isPartOf": {"@type": "WebSite", "name": "Servala", "url": base_url},
        }

    elif view_name == "partner_list":
        data = {
            "@context": "https://schema.org",
            "@type": "CollectionPage",
            "name": "Consulting Partners - Servala",
            "url": f"{base_url}/partners/",
            "description": "Browse our network of expert consulting partners on Servala who can help implement and optimize cloud services.",
            "isPartOf": {"@type": "WebSite", "name": "Servala", "url": base_url},
        }

    elif view_name == "service_detail" and "service" in context:
        service = context["service"]
        service_url = request.build_absolute_uri()

        data = {
            "@context": "https://schema.org",
            "@type": "Product",
            "name": service.name,
            "description": service.description,
            "url": service_url,
            "category": "Cloud Service",
        }

        # Add image if available
        if hasattr(service, "logo") and service.logo:
            data["image"] = request.build_absolute_uri(service.logo.url)

        # Add offerings if available
        if hasattr(service, "offerings") and service.offerings.exists():
            data["offers"] = {
                "@type": "AggregateOffer",
                "availability": "https://schema.org/InStock",
                "offerCount": service.offerings.count(),
            }

    elif view_name == "provider_detail" and "provider" in context:
        provider = context["provider"]
        provider_url = request.build_absolute_uri()

        data = {
            "@context": "https://schema.org",
            "@type": "Organization",
            "name": provider.name,
            "description": provider.description,
            "url": provider_url,
        }

        # Add image if available
        if hasattr(provider, "logo") and provider.logo:
            data["logo"] = request.build_absolute_uri(provider.logo.url)

        # Add contact information if available
        contact_point = {"@type": "ContactPoint", "contactType": "Customer Support"}

        if hasattr(provider, "website") and provider.website:
            contact_point["url"] = provider.website
        if hasattr(provider, "email") and provider.email:
            contact_point["email"] = provider.email
        if hasattr(provider, "phone") and provider.phone:
            contact_point["telephone"] = provider.phone

        if len(contact_point) > 2:  # If we have more than the @type and contactType
            data["contactPoint"] = contact_point

        # Add address if available
        if hasattr(provider, "address") and provider.address:
            data["address"] = {
                "@type": "PostalAddress",
                "addressCountry": "CH",  # Default to Switzerland
            }

    elif view_name == "partner_detail" and "partner" in context:
        partner = context["partner"]
        partner_url = request.build_absolute_uri()

        data = {
            "@context": "https://schema.org",
            "@type": "Organization",
            "name": partner.name,
            "description": partner.description,
            "url": partner_url,
        }

        # Add image if available
        if hasattr(partner, "logo") and partner.logo:
            data["logo"] = request.build_absolute_uri(partner.logo.url)

        # Add contact information if available
        contact_point = {"@type": "ContactPoint", "contactType": "Customer Support"}

        if hasattr(partner, "website") and partner.website:
            contact_point["url"] = partner.website
        if hasattr(partner, "email") and partner.email:
            contact_point["email"] = partner.email
        if hasattr(partner, "phone") and partner.phone:
            contact_point["telephone"] = partner.phone

        if len(contact_point) > 2:  # If we have more than the @type and contactType
            data["contactPoint"] = contact_point

        # Add address if available
        if hasattr(partner, "address") and partner.address:
            data["address"] = {
                "@type": "PostalAddress",
                "addressCountry": "CH",  # Default to Switzerland
            }

    elif view_name == "offering_detail" and "offering" in context:
        offering = context["offering"]
        offering_url = request.build_absolute_uri()

        data = {
            "@context": "https://schema.org",
            "@type": "Product",
            "name": f"{offering.service.name} on {offering.cloud_provider.name}",
            "description": offering.description or offering.service.description,
            "url": offering_url,
            "category": "Cloud Service",
        }

        # Add brand (service)
        data["brand"] = {"@type": "Brand", "name": offering.service.name}

        # Add image if available
        if hasattr(offering.service, "logo") and offering.service.logo:
            data["image"] = request.build_absolute_uri(offering.service.logo.url)

        # Add offers if available
        if hasattr(offering, "plans") and offering.plans.exists():
            data["offers"] = {
                "@type": "AggregateOffer",
                "availability": "https://schema.org/InStock",
                "offerCount": offering.plans.count(),
                "seller": {
                    "@type": "Organization",
                    "name": offering.cloud_provider.name,
                    "url": request.build_absolute_uri(
                        offering.cloud_provider.get_absolute_url()
                    ),
                },
            }

    else:
        # Default to organization data if no specific page type matches
        data = organization_data

    # Return the JSON-LD as a script tag
    json_ld = json.dumps(data, indent=2)
    return mark_safe(f'<script type="application/ld+json">{json_ld}</script>')
