# hub/services/templatetags/contact_tags.py
from django import template
from hub.services.forms import LeadForm
from hub.services.models import Service, ServiceOffering, Plan

register = template.Library()


@register.inclusion_tag("services/embedded_contact_form.html", takes_context=True)
def embedded_contact_form(
    context, source=None, details=None, service=None, offering_id=None, plan_id=None
):
    """
    Renders an embedded contact form with optional service context information.

    Usage:
    {% load contact_tags %}
    {% embedded_contact_form source="Partner Page" details="ACME Corp" %}
    {% embedded_contact_form service=service offering_id=offering.id plan_id=plan.id %}
    """
    request = context["request"]
    form = LeadForm()

    service_obj = None
    offering_obj = None
    plan_obj = None

    # Resolve service/offering/plan objects if IDs provided
    if service and isinstance(service, str):
        try:
            service_obj = Service.objects.get(slug=service)
        except Service.DoesNotExist:
            pass
    elif service:
        service_obj = service

    if offering_id and service_obj:
        try:
            offering_obj = ServiceOffering.objects.get(
                id=offering_id, service=service_obj
            )
        except ServiceOffering.DoesNotExist:
            pass

    if plan_id and offering_obj:
        try:
            plan_obj = Plan.objects.get(id=plan_id, offering=offering_obj)
        except Plan.DoesNotExist:
            pass

    return {
        "form": form,
        "source": source,
        "details": details,
        "service": service_obj,
        "offering": offering_obj,
        "plan": plan_obj,
        "request": request,
    }
