"""SEO endpoints: robots.txt, sitemap.xml, and structured-data helpers.

These endpoints make alexanderwhitestone.com crawlable by search engines.
All pages listed in the sitemap are server-rendered HTML (not SPA-only).
"""

from __future__ import annotations

from datetime import date

from fastapi import APIRouter
from fastapi.responses import PlainTextResponse, Response

from config import settings

router = APIRouter(tags=["seo"])

# Public-facing pages included in the sitemap.
# Format: (path, change_freq, priority)
_SITEMAP_PAGES: list[tuple[str, str, str]] = [
    ("/", "daily", "1.0"),
    ("/briefing", "daily", "0.9"),
    ("/tasks", "daily", "0.8"),
    ("/calm", "weekly", "0.7"),
    ("/thinking", "weekly", "0.7"),
    ("/swarm/mission-control", "weekly", "0.7"),
    ("/monitoring", "weekly", "0.6"),
    ("/nexus", "weekly", "0.6"),
    ("/spark/ui", "weekly", "0.6"),
    ("/memory", "weekly", "0.6"),
    ("/marketplace/ui", "weekly", "0.8"),
    ("/models", "weekly", "0.5"),
    ("/tools", "weekly", "0.5"),
    ("/scorecards", "weekly", "0.6"),
]


@router.get("/robots.txt", response_class=PlainTextResponse)
async def robots_txt() -> str:
    """Allow all search engines; point to sitemap."""
    base = settings.site_url.rstrip("/")
    return f"User-agent: *\nAllow: /\n\nSitemap: {base}/sitemap.xml\n"


@router.get("/sitemap.xml")
async def sitemap_xml() -> Response:
    """Generate XML sitemap for all crawlable pages."""
    base = settings.site_url.rstrip("/")
    today = date.today().isoformat()

    url_entries: list[str] = []
    for path, changefreq, priority in _SITEMAP_PAGES:
        url_entries.append(
            f"  <url>\n"
            f"    <loc>{base}{path}</loc>\n"
            f"    <lastmod>{today}</lastmod>\n"
            f"    <changefreq>{changefreq}</changefreq>\n"
            f"    <priority>{priority}</priority>\n"
            f"  </url>"
        )

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