from django.shortcuts import render
from django.urls import reverse, NoReverseMatch


APP_ERROR_BRANDING = {
    "expat_life": {
        "path_keywords": ["/"],
        "brand_name": "Ensolanka Live in Sri Lanka",
        "tagline": "Affordable Tropical Living",
        "base_template": "expat_life/base.html",
        "home_url_name": "expat_life:home",
        "primary_label": "Back to Live in Sri Lanka",
        "theme_class": "error-theme-expat",
    },
    "rental_app": {
        "path_keywords": ["/rentals/"],
        "brand_name": "Ensolanka Rent in Sri Lanka",
        "tagline": "List Local. Reach Global.",
        "base_template": "rental_app/base_rental.html",
        "home_url_name": "rental_app:home_rental",
        "primary_label": "Back to Rent in Sri Lanka",
        "theme_class": "error-theme-rental",
    },
    "dating_app": {
        "path_keywords": ["/dating/"],
        "brand_name": "Ensolanka Date in Sri Lanka",
        "tagline": "Connect Locally, Love Globally",
        "base_template": "dating_app/base_dating.html",
        "home_url_name": "dating_app:home_dating",
        "primary_label": "Back to Date in Sri Lanka",
        "theme_class": "error-theme-dating",
    },
    "service_partner_app": {
        "path_keywords": ["/assistants/"],
        "brand_name": "Ensolanka Hired in Sri Lanka",
        "tagline": "Local Skills. Global Pay",
        "base_template": "service_partner_app/base_service_partner.html",
        "home_url_name": "service_partner_app:home_service_partner",
        "primary_label": "Back to Hired in Sri Lanka",
        "theme_class": "error-theme-service",
    },
    "affiliates_app": {
        "path_keywords": ["/affiliates/"],
        "brand_name": "Partner with Ensolanka",
        "tagline": "Grow Together. Earn Together.",
        "base_template": "affiliates_app/base_affiliate.html",
        "home_url_name": "affiliates_app:home_affiliates",
        "primary_label": "Back to Partner with Ensolanka",
        "theme_class": "error-theme-affiliates",
    },
    "property_manager_app": {
        "path_keywords": ["/property-care/"],
        "brand_name": "Ensolanka Home in Sri Lanka",
        "tagline": "Remote owners, local maintenance.",
        "base_template": "property_manager_app/base_property_manager.html",
        "home_url_name": "property_manager_app:home_property_manager",
        "primary_label": "Back to Home in Sri Lanka",
        "theme_class": "error-theme-property",
    },
    "hosting_app": {
        "path_keywords": ["/hosting/"],
        "brand_name": "Ensolanka Host in Sri Lanka",
        "tagline": "Be the place couples choose",
        "base_template": "hosting_app/base_hosting.html",
        "home_url_name": "hosting_app:home_hosting",
        "primary_label": "Back to Host in Sri Lanka",
        "theme_class": "error-theme-hosting",
    },
}


DEFAULT_ERROR_BRANDING = {
    "brand_name": "Ensolanka",
    "tagline": "Digital solutions for global opportunities.",
    "base_template": "expat_life/base.html",
    "home_url_name": "expat_life:home",
    "primary_label": "Back to Home",
    "theme_class": "error-theme-default",
}


def get_error_branding(request):
    path = request.path.lower()

    for app_key, branding in APP_ERROR_BRANDING.items():
        for keyword in branding.get("path_keywords", []):
            if keyword != "/" and path.startswith(keyword):
                return branding.copy()

    return APP_ERROR_BRANDING.get("expat_life", DEFAULT_ERROR_BRANDING).copy()


def add_safe_home_url(context):
    """
    Prevents the error page from crashing if a URL name is wrong.
    """
    home_url_name = context.get("home_url_name")

    try:
        context["home_url"] = reverse(home_url_name)
    except NoReverseMatch:
        context["home_url"] = "/"

    return context


def custom_404(request, exception=None):
    context = get_error_branding(request)
    context.update({
        "error_code": "404",
        "error_title": "Page Not Found",
        "error_message": "The page you are looking for may have been moved, renamed, or is no longer available.",
        "error_hint": "Please return to the main section and continue from there.",
    })
    context = add_safe_home_url(context)
    return render(request, "errors/404.html", context, status=404)


def custom_500(request):
    context = DEFAULT_ERROR_BRANDING.copy()
    context.update({
        "error_code": "500",
        "error_title": "Something Went Wrong",
        "error_message": "We could not complete your request due to a temporary server issue.",
        "error_hint": "Please try again shortly or contact support if the issue continues.",
    })
    context = add_safe_home_url(context)
    return render(request, "errors/500.html", context, status=500)


def custom_403(request, exception=None):
    context = get_error_branding(request)
    context.update({
        "error_code": "403",
        "error_title": "Access Restricted",
        "error_message": "You do not have permission to access this page or resource.",
        "error_hint": "Please login with the correct account or return to your dashboard.",
    })
    context = add_safe_home_url(context)
    return render(request, "errors/403.html", context, status=403)


def custom_400(request, exception=None):
    context = get_error_branding(request)
    context.update({
        "error_code": "400",
        "error_title": "Invalid Request",
        "error_message": "The request could not be processed because something was incorrect or incomplete.",
        "error_hint": "Please go back, check the details, and try again.",
    })
    context = add_safe_home_url(context)
    return render(request, "errors/400.html", context, status=400)