import json

from django.conf import settings
from django.urls import reverse

from .seo import PUBLIC_PAGE_ENTRIES, get_service_entries


def tianji_tracking(request):
    return {
        'tianji_enabled': getattr(settings, 'TIANJI_ENABLED', True),
        'tianji_tracker_url': getattr(
            settings,
            'TIANJI_TRACKER_URL',
            'https://tianji.aimloperations.com/tracker.js',
        ),
        'tianji_website_id': getattr(
            settings,
            'TIANJI_WEBSITE_ID',
            'cm7w80pyy020oddswy2evl957',
        ),
        'page_name': getattr(getattr(request, 'resolver_match', None), 'url_name', ''),
    }


def webmcp_context(request):
    page_name = getattr(getattr(request, 'resolver_match', None), 'url_name', '')
    services = [
        {
            **entry,
            "url": request.build_absolute_uri(reverse(entry["slug"])),
        }
        for entry in get_service_entries()
    ]
    page_lookup = {
        url_name: {
            "slug": url_name,
            "name": title,
            "summary": summary,
            "url": request.build_absolute_uri(reverse(url_name)),
        }
        for url_name, title, _changefreq, _priority, summary in PUBLIC_PAGE_ENTRIES
    }

    return {
        'webmcp_enabled': getattr(settings, 'WEBMCP_ENABLED', False),
        'webmcp_page_name': page_name,
        'webmcp_contact_url': request.build_absolute_uri(reverse('contact')),
        'webmcp_recaptcha_required': not settings.DEBUG,
        'webmcp_services_json': json.dumps(services),
        'webmcp_pages_json': json.dumps(page_lookup),
    }
