"""
Context processors for the core app.

This module provides context processors that add useful utilities
and data to template contexts across the application.

Available Context Processors:
    - fsm_context: FSM state machine utilities
    - breadcrumbs: Breadcrumb navigation data
    - page_meta: Page metadata for SEO and social sharing
"""

from __future__ import annotations

import json
from typing import TYPE_CHECKING, Any

from django_fsm import can_proceed

from .state_machine.exceptions import format_transition_error
from .state_machine.mixins import TRANSITION_METADATA
from .utils.breadcrumbs import Breadcrumb, BreadcrumbBuilder, breadcrumbs_to_schema

if TYPE_CHECKING:
    from django.http import HttpRequest


def fsm_context(request: HttpRequest) -> dict[str, Any]:
    """
    Add FSM utilities to template context.

    This context processor makes FSM-related utilities available in all
    templates, enabling easier integration of state machine functionality.

    Available context variables:
        - can_proceed: Function to check if a transition can proceed
        - format_transition_error: Function to format FSM exceptions
        - TRANSITION_METADATA: Dictionary of default transition metadata

    Usage in templates:
        {% if can_proceed(submission.transition_to_approved, request.user) %}
            <button>Approve</button>
        {% endif %}

    Returns:
        Dictionary of FSM utilities
    """
    return {
        "can_proceed": can_proceed,
        "format_transition_error": format_transition_error,
        "TRANSITION_METADATA": TRANSITION_METADATA,
    }


def breadcrumbs(request: HttpRequest) -> dict[str, Any]:
    """
    Add breadcrumb utilities to template context.

    This context processor provides breadcrumb-related utilities and data
    to all templates. Views can override the default breadcrumbs by setting
    `request.breadcrumbs` before the context processor runs.

    Available context variables:
        - breadcrumbs: List of Breadcrumb instances (from view or auto-generated)
        - breadcrumbs_json: JSON-LD Schema.org BreadcrumbList for SEO
        - BreadcrumbBuilder: Class for building breadcrumbs in templates
        - build_breadcrumb: Function for creating single breadcrumb items

    Usage in views:
        def park_detail(request, slug):
            park = get_object_or_404(Park, slug=slug)
            request.breadcrumbs = [
                build_breadcrumb('Home', '/', icon='fas fa-home'),
                build_breadcrumb('Parks', reverse('parks:list')),
                build_breadcrumb(park.name, is_current=True),
            ]
            return render(request, 'parks/detail.html', {'park': park})

    Usage in templates:
        {% if breadcrumbs %}
            {% include 'components/navigation/breadcrumbs.html' %}
        {% endif %}

        {# For Schema.org structured data #}
        <script type="application/ld+json">{{ breadcrumbs_json|safe }}</script>

    Returns:
        Dictionary with breadcrumb utilities and data
    """
    from .utils.breadcrumbs import build_breadcrumb

    # Get breadcrumbs from request if set by view
    crumbs: list[Breadcrumb] = getattr(request, "breadcrumbs", [])

    # Generate Schema.org JSON-LD
    breadcrumbs_json = ""
    if crumbs:
        schema = breadcrumbs_to_schema(crumbs, request)
        breadcrumbs_json = json.dumps(schema)

    return {
        "breadcrumbs": crumbs,
        "breadcrumbs_json": breadcrumbs_json,
        "BreadcrumbBuilder": BreadcrumbBuilder,
        "build_breadcrumb": build_breadcrumb,
    }


def page_meta(request: HttpRequest) -> dict[str, Any]:
    """
    Add page metadata utilities to template context.

    This context processor provides default values and utilities for
    page metadata including titles, descriptions, and social sharing tags.
    Views can override defaults by setting attributes on the request.

    Available context variables:
        - site_name: Default site name ('ThrillWiki')
        - default_description: Default meta description
        - default_og_image: Default Open Graph image URL

    Request attributes that views can set:
        - request.page_title: Override page title
        - request.meta_description: Override meta description
        - request.og_image: Override Open Graph image
        - request.og_type: Override Open Graph type
        - request.canonical_url: Override canonical URL

    Usage in views:
        def park_detail(request, slug):
            park = get_object_or_404(Park, slug=slug)
            request.page_title = f'{park.name} - Parks - ThrillWiki'
            request.meta_description = park.description[:160]
            request.og_image = park.featured_image.url if park.featured_image else None
            request.og_type = 'place'
            return render(request, 'parks/detail.html', {'park': park})

    Returns:
        Dictionary with page metadata
    """
    from django.templatetags.static import static

    return {
        "site_name": "ThrillWiki",
        "default_description": "ThrillWiki - Your comprehensive guide to theme parks and roller coasters",
        "default_og_image": static("images/og-default.jpg"),
        # Pass through any request-level overrides
        "page_title": getattr(request, "page_title", None),
        "meta_description": getattr(request, "meta_description", None),
        "og_image": getattr(request, "og_image", None),
        "og_type": getattr(request, "og_type", "website"),
        "canonical_url": getattr(request, "canonical_url", None),
    }
