"""Infrakinetic delivered pages: server snippet for Python (Django, Flask, any WSGI/ASGI app).

Site Builder Studio §9.3, connector 3. Standard library only. https://developers.infrakinetic.in/server.html

    from infrakinetic import infrakinetic_page, hydrate_tag, purge_endpoint
    page = infrakinetic_page(request.path)      # None: not ours, show your own page or 404
    # template: {{ page.head_html|safe }} in <head>, {{ page.html|safe }} where content goes,
    #           {{ hydrate_tag(page)|safe }} before </body>

INFRAKINETIC_RENDER_KEY and INFRAKINETIC_SITE_URL come from the environment (never from the Host
header). Copies are cached on disk with their ETag; if our service cannot be reached, the last good
copy is served for up to 7 days. Licence: MIT.
"""
import hashlib
import hmac
import html
import json
import os
import re
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request

_SITE = re.compile(r"^https://[a-z0-9.-]+(:\d+)?$", re.I)
_API = re.compile(r"^(https://[a-z0-9.-]+(:\d+)?|http://(localhost|127\.0\.0\.1)(:\d+)?)$", re.I)
STALE_SECONDS = 7 * 86400


def _cache_dir():
    d = os.environ.get("INFRAKINETIC_CACHE_DIR") or os.path.join(tempfile.gettempdir(), "infrakinetic-pages")
    os.makedirs(d, mode=0o700, exist_ok=True)
    return d


def _file_for(url):
    return os.path.join(_cache_dir(), hashlib.sha256(url.encode("utf-8")).hexdigest() + ".json")


def _read(path):
    try:
        with open(path, encoding="utf-8") as f:
            return json.load(f)
    except (OSError, ValueError):
        return None


def _write(path, value):
    with open(path, "w", encoding="utf-8") as f:
        json.dump(value, f)


def _stale(held):
    return held["page"] if held and time.time() - held["at"] < STALE_SECONDS else None


def infrakinetic_page(request_path):
    key = os.environ.get("INFRAKINETIC_RENDER_KEY", "")
    site = os.environ.get("INFRAKINETIC_SITE_URL", "").rstrip("/")
    api = (os.environ.get("INFRAKINETIC_API_URL") or "https://api.infrakinetic.in").rstrip("/")
    if not key or not _SITE.match(site) or not _API.match(api):
        return None
    if not isinstance(request_path, str) or not request_path.startswith("/") or request_path.startswith("//") or len(request_path) > 1500:
        return None
    url = site + request_path
    path = _file_for(url)
    held = _read(path)
    if held and time.time() - held["at"] < held["page"].get("cache", {}).get("max_age", 60):
        return held["page"]
    headers = {"Authorization": "Bearer " + key, "Accept": "application/json", "User-Agent": "infrakinetic-python/1"}
    if held:
        headers["If-None-Match"] = held["page"]["cache"]["etag"]
    req = urllib.request.Request(api + "/api/delivery/v1/page?url=" + urllib.parse.quote(url, safe=""), headers=headers)
    try:
        # The API address is checked above (https, or a local test server); never a user-supplied host.
        with urllib.request.urlopen(req, timeout=5) as res:  # nosemgrep: dynamic-urllib-use-detected
            page = json.loads(res.read().decode("utf-8"))
    except urllib.error.HTTPError as err:
        if err.code == 304 and held:
            _write(path, {"at": time.time(), "page": held["page"]})
            return held["page"]
        if err.code == 404:
            try:
                os.remove(path)
            except OSError:
                pass
            return None
        return _stale(held)
    except (urllib.error.URLError, OSError, ValueError):
        return _stale(held)
    if not isinstance(page, dict) or page.get("status") != 200 or not isinstance(page.get("html"), str) or not (page.get("hydrate") or {}).get("src"):
        return None
    _write(path, {"at": time.time(), "page": page})
    return page


def hydrate_tag(page):
    h = (page or {}).get("hydrate") or {}
    if not str(h.get("src", "")).startswith("https://"):
        return ""
    return '<script src="%s" integrity="%s" crossorigin="anonymous" defer></script>' % (
        html.escape(h["src"], quote=True), html.escape(h.get("integrity", ""), quote=True))


def verify_signature(header, raw, secrets, tolerance=300):
    """True when header (x-infrakinetic-signature) carries a valid v1 HMAC-SHA256 of "t.body" within five minutes."""
    t, given = None, []
    for part in str(header or "").split(","):
        k, _, v = part.strip().partition("=")
        if k == "t" and v.isdigit():
            t = int(v)
        elif k == "v1":
            given.append(v.lower())
    if t is None or abs(time.time() - t) > tolerance or not given:
        return False
    for secret in secrets:
        if len(secret) < 16:
            continue
        expected = hmac.new(secret.encode("utf-8"), ("%d." % t).encode("utf-8") + raw, hashlib.sha256).hexdigest()
        if any(hmac.compare_digest(expected, g) for g in given):
            return True
    return False


def purge(body):
    """Drops the cached copies a verified purge body (webhook or changes-feed item) names."""
    data = body.get("data") if isinstance(body, dict) else None
    src = (data or {}).get("record") or data or body or {}
    site = os.environ.get("INFRAKINETIC_SITE_URL", "").rstrip("/")
    purged = 0
    for url in list(src.get("urls") or [])[:500]:
        if isinstance(url, str) and url.startswith(site + "/"):
            try:
                os.remove(_file_for(url))
            except OSError:
                pass
            purged += 1
    everything = any(re.match(r"^ik-(area|website)-", str(t)) for t in (src.get("tags") or []))
    if everything:
        for name in os.listdir(_cache_dir()):
            if name.endswith(".json"):
                os.remove(os.path.join(_cache_dir(), name))
    return {"ok": True, "purged": purged, "all": everything}


def purge_endpoint(raw_body, signature_header):
    """The purge webhook. raw_body: the request's bytes. Returns (status, dict)."""
    secrets = [s.strip() for s in os.environ.get("INFRAKINETIC_WEBHOOK_SECRET", "").split(",") if s.strip()]
    if not verify_signature(signature_header, raw_body, secrets):
        return 401, {"error": "Signature check failed"}
    try:
        body = json.loads(raw_body.decode("utf-8"))
    except ValueError:
        return 400, {"error": "Bad body"}
    return 200, purge(body)
