"""
sitemap.xml / robots.txt — generated live from the DB rather than a static
build-time file, since businesses/products/categories change constantly.
Mounted at the project root (not under /api) in business_platform/urls.py
so they land at the conventional /sitemap.xml and /robots.txt paths.

In production, the public-facing domain (the Vite SPA's static host) needs a
reverse-proxy rule forwarding GET /sitemap.xml and GET /robots.txt to this
Django backend, since the SPA itself has no server-side runtime to generate
these at request time.
"""
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.http import require_GET

from .models import Business, Category, Service

STATIC_PAGES = [
    ("", "1.0", "daily"),
    ("search", "0.8", "daily"),
    ("categories", "0.7", "weekly"),
    ("offers", "0.8", "daily"),
    ("how-it-works", "0.5", "monthly"),
    ("for-businesses", "0.6", "monthly"),
    ("pricing", "0.6", "monthly"),
]


def _site_url():
    return getattr(settings, 'FRONTEND_URL', 'http://localhost:5173').rstrip('/')


def _url_entry(loc, lastmod=None, changefreq=None, priority=None):
    parts = [f"  <url>\n    <loc>{loc}</loc>"]
    if lastmod:
        parts.append(f"    <lastmod>{lastmod.date().isoformat()}</lastmod>")
    if changefreq:
        parts.append(f"    <changefreq>{changefreq}</changefreq>")
    if priority:
        parts.append(f"    <priority>{priority}</priority>")
    parts.append("  </url>")
    return "\n".join(parts)


@require_GET
def sitemap_xml(request):
    site = _site_url()
    entries = [
        _url_entry(f"{site}/{path}", changefreq=freq, priority=pri)
        for path, pri, freq in STATIC_PAGES
    ]

    for cat in Category.objects.filter(is_active=True).only('slug'):
        entries.append(_url_entry(f"{site}/category/{cat.slug}", changefreq="weekly", priority="0.6"))

    for biz in Business.objects.filter(is_active=True).only('slug', 'updated_at'):
        entries.append(_url_entry(f"{site}/business/{biz.slug}", lastmod=biz.updated_at, changefreq="weekly", priority="0.7"))

    for svc in Service.objects.filter(is_active=True, business__is_active=True).only('slug', 'created_at'):
        entries.append(_url_entry(f"{site}/product/{svc.slug}", lastmod=svc.created_at, changefreq="weekly", priority="0.5"))

    xml = (
        '<?xml version="1.0" encoding="UTF-8"?>\n'
        '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
        + "\n".join(entries) +
        "\n</urlset>"
    )
    return HttpResponse(xml, content_type="application/xml")


@require_GET
def robots_txt(request):
    site = _site_url()
    lines = [
        "User-agent: *",
        "Allow: /",
        "Disallow: /account",
        "Disallow: /requests",
        "Disallow: /saved",
        "Disallow: /following",
        "Disallow: /notifications",
        "Disallow: /403",
        "Disallow: /500",
        f"Sitemap: {site}/sitemap.xml",
    ]
    return HttpResponse("\n".join(lines), content_type="text/plain")
