"""SEO infrastructure routes: /robots.txt and /sitemap.xml.

Generated dynamically so they stay in sync as we add types, content
pages, or public saved builds — no manual sitemap maintenance.

robots.txt: Allows crawl of public content; disallows the working-draft
build page, auth flows, and the affiliate jump.cgi (no content there to
index). Points at the absolute sitemap URL.

sitemap.xml: Home + static content + /browse?type=<each> + every
public saved build (status='public', is_latest=1). Capped at 5000
build URLs for now — well under Google's 50k/sitemap limit, and our
total saved-builds count is much smaller. Includes lastmod where we
can derive one cheaply.

Both routes use PUBLIC_URL_ROOT (set in passenger_wsgi.py / config.ini)
for absolute URLs rather than request.host_url so canonicalization is
not bypassed by a stray Host: header. Dev fallback to request.host_url
since dev is not crawled.

On staging, the deploy script writes a static `public/robots.txt` with
`Disallow: /` for lockdown; Apache serves it directly and never reaches
this view. On prod (lockdown=0), no static robots.txt exists and the
Flask route handles it.

See site-ng/docs/seo.md §D for the spec.
"""

from xml.sax.saxutils import escape as xml_escape

from flask import (Blueprint, Response, current_app, request,
                   send_from_directory)

from ..labels import TYPE_LABELS

bp = Blueprint("seo", __name__)


@bp.route("/favicon.ico")
def favicon():
    """Serve the favicon at the root path browsers/bots auto-request (it 404'd
    otherwise — passenger handles /favicon.ico, no Apache static file at root).
    Stopgap legacy icon until a redesigned one lands (see TODO)."""
    return send_from_directory(current_app.static_folder, "favicon.ico",
                               mimetype="image/x-icon", max_age=86400)


def _public_url_root() -> str:
    """Mirror of the _inject_public_url_root context_processor in
    __init__.py — same fallback chain. Kept in a helper so both routes
    + any future SEO code use one source of truth."""
    root = (current_app.config.get("PUBLIC_URL_ROOT") or "").rstrip("/")
    if not root:
        try:
            root = request.host_url.rstrip("/")
        except RuntimeError:
            root = ""
    return root


@bp.route("/robots.txt")
def robots_txt():
    root = _public_url_root()
    lines = [
        "# arpartsfinder.com — see site-ng/docs/seo.md",
        "",
        "User-agent: *",
        "Allow: /",
        # Working-draft build page; not a stable shareable URL.
        # Saved builds at /b/<code> ARE indexable (in sitemap).
        "Disallow: /build",
        # Auth flows (no content; /auth/<token> is single-use).
        "Disallow: /login",
        "Disallow: /auth/",
        # User-specific pages (no value to index even if reachable).
        "Disallow: /my-builds",
        # POST-only form target.
        "Disallow: /report-category",
        # Affiliate redirect — no content to index, just outbound.
        # /jump is the canonical route; /jump.cgi is the legacy alias.
        "Disallow: /jump",
        "Disallow: /jump.cgi",
        "",
        f"Sitemap: {root}/sitemap.xml",
        "",
    ]
    return Response("\n".join(lines), mimetype="text/plain")


@bp.route("/sitemap.xml")
def sitemap_xml():
    root = _public_url_root()

    urls = []

    # Home page.
    urls.append({
        "loc": f"{root}/",
        "changefreq": "daily",
        "priority": "1.0",
    })

    # Static content pages — visit cadence reflects how often they
    # meaningfully change. /changelog is "weekly" because new entries
    # land in bursts; /terms is "yearly" because it almost never
    # changes; /faq + /resources land in the middle.
    for path, freq, prio in (
        ("/faq", "monthly", "0.6"),
        ("/resources", "monthly", "0.6"),
        ("/terms", "yearly", "0.3"),
        ("/changelog", "weekly", "0.7"),
    ):
        urls.append({
            "loc": f"{root}{path}",
            "changefreq": freq,
            "priority": prio,
        })

    # /browse base + per-type. Each type-filter page is a
    # long-tail-keyword landing page ("AR-15 stripped uppers in
    # stock", etc.) so they're high priority. The base /browse is
    # also indexable as the no-filter landing page.
    urls.append({
        "loc": f"{root}/browse",
        "changefreq": "daily",
        "priority": "0.9",
    })
    for code in sorted(TYPE_LABELS.keys()):
        urls.append({
            "loc": f"{root}/browse?type={code}",
            "changefreq": "daily",
            "priority": "0.8",
        })

    # Public saved builds — every shared kit is a long-tail backlink
    # candidate per seo.md §B. Cap at 5000 (well under Google's
    # 50k/sitemap limit; if we ever blow past it, paginate the
    # sitemap by year or by code prefix). Order by `updated` so the
    # most recent shareable builds are first if a crawler stops
    # partway. Use the SLUGGED form of the URL (matches the canonical
    # the build's page declares); we also need each build's items
    # for the slug, so a small per-build query happens here. Profane-
    # titled builds are noindex'd by the build view itself, so we
    # exclude them from the sitemap (don't waste Google's crawl
    # budget pointing at pages we tell it to ignore).
    try:
        from ..db import get_db
        from ..build_url import build_slug, is_profane
        from .. import saves as _saves
        cur = get_db().cursor()
        cur.execute(
            "SELECT id, code, title, updated FROM build "
            "WHERE status='public' AND is_latest=1 "
            "ORDER BY updated DESC LIMIT 5000")
        builds = cur.fetchall()
        cur.close()
        for row in builds:
            if is_profane(row.get("title")):
                # noindex'd in the view; skip in sitemap too.
                continue
            items = _saves.get_items(row["id"])
            slug = build_slug(row.get("title"), items)
            entry = {
                "loc": f"{root}/b/{row['code']}/{slug}",
                "changefreq": "weekly",
                "priority": "0.7",
            }
            if row.get("updated"):
                entry["lastmod"] = row["updated"].strftime("%Y-%m-%d")
            urls.append(entry)
    except Exception:
        current_app.logger.exception(
            "sitemap: failed to enumerate public builds")
        # Don't let a DB hiccup take down the sitemap — return what
        # we have so far rather than 500. Static URLs are still
        # valuable on their own.

    # Product detail pages (/p/<id>/<slug>). Every IN-STOCK product is an
    # indexable long-tail page (exact part + price + history). We list
    # in-stock only — OOS product pages still exist and are reachable via
    # internal links, but we don't spend crawl budget pointing Google at
    # things that aren't currently buyable. Newest first so a crawler that
    # stops partway gets the freshest. Cap well under Google's 50k/sitemap
    # limit; if the in-stock catalog ever blows past it, split into a
    # sitemap index (by type or id range) — same TODO as the builds cap.
    try:
        from ..db import get_db
        from ..product_url import product_slug
        cur = get_db().cursor()
        cur.execute(
            "SELECT id, description, added FROM parts "
            "WHERE instock=1 ORDER BY added DESC LIMIT 45000")
        for row in cur.fetchall():
            entry = {
                "loc": f"{root}/p/{row['id']}/{product_slug(row['description'])}",
                "changefreq": "daily",
                "priority": "0.6",
            }
            if row.get("added"):
                entry["lastmod"] = row["added"].strftime("%Y-%m-%d")
            urls.append(entry)
        cur.close()
    except Exception:
        current_app.logger.exception(
            "sitemap: failed to enumerate product pages")

    # Build the XML.
    out = ['<?xml version="1.0" encoding="UTF-8"?>',
           '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">']
    for u in urls:
        out.append("  <url>")
        out.append(f"    <loc>{xml_escape(u['loc'])}</loc>")
        if "lastmod" in u:
            out.append(f"    <lastmod>{u['lastmod']}</lastmod>")
        out.append(f"    <changefreq>{u['changefreq']}</changefreq>")
        out.append(f"    <priority>{u['priority']}</priority>")
        out.append("  </url>")
    out.append("</urlset>")
    out.append("")

    return Response("\n".join(out), mimetype="application/xml")
