"""Verify private-origin refusal, retained aliases and the public edge's exact build."""
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import time

from edge_inputs import load, TOKEN_HEADER
from edge_vhost import NGINX_DIR, paths, recorded_domain


def request(url, *, headers=None, run=subprocess.run):
    # curl retains its strict TLS/time bounds. Private headers and bounded response
    # bytes live only in an owned mode-0700 directory, never argv or diagnostics.
    with tempfile.TemporaryDirectory(prefix="backend-edge-health-") as directory:
        root = Path(directory)
        config, body = root / "curl.conf", root / "body"
        config.write_text("".join(f'header = "{key}: {value}"\n' for key, value in (headers or {}).items()))
        config.chmod(0o600)
        result = run(["curl", "--disable", "--silent", "--config", str(config), "--output", str(body),
                      "--write-out", "%{http_code}", "--proto", "=https", "--connect-timeout", "5",
                      "--max-time", "10", "--max-filesize", "65536", url],
                     capture_output=True, timeout=15)
        status = result.stdout.decode("ascii", errors="replace")
        data = body.read_bytes() if body.exists() and body.stat().st_size <= 65536 else b""
        return result.returncode, int(status) if status.isdigit() else 0, data


def healthy(url, sha="", *, headers=None, fetch=request, sleep=time.sleep):
    for attempt in range(15):
        try:
            code, status, body = fetch(url, headers=headers)
            valid = code == 0 and 200 <= status < 300
            if valid and sha:
                value = json.loads(body)
                valid = isinstance(value, dict) and value.get("build_sha") == sha
            if valid:
                return
        except (OSError, ValueError, subprocess.SubprocessError):
            pass
        if attempt != 14:
            sleep(2)
    raise ValueError("backend_public_health_failed")


def verify(config, app, domain, health, *, nginx_dir=NGINX_DIR, fetch=request, sleep=time.sleep):
    value = load(config)
    if not health.startswith("/") or any(character in health for character in "\r\n?#"):
        raise ValueError("backend_health_path_invalid")
    origin_url = f"https://{domain}{health}"
    if value["ingress_required"] == "true":
        for headers in (None, {TOKEN_HEADER: "invalid-backend-ingress-token"}):
            code, status, _body = fetch(origin_url, headers=headers)
            if code != 0 or status != 403:
                raise ValueError("backend_origin_ingress_unverified")
        healthy(origin_url, value["expected_build_sha"], headers={TOKEN_HEADER: value["ingress_token"]},
                fetch=fetch, sleep=sleep)
        legacy = recorded_domain(paths(config, app, nginx_dir)[0])
        if legacy:
            healthy(f"https://{legacy}{health}", fetch=fetch, sleep=sleep)
    public = value["public_health_url"] or origin_url
    healthy(public, value["expected_build_sha"], fetch=fetch, sleep=sleep)
    return {"ok": True, "public_health_verified": True, "build_sha": value["expected_build_sha"],
            "ingress_verified": value["ingress_required"] == "true"}


if __name__ == "__main__":
    try:
        print(json.dumps(verify(*sys.argv[1:5])))
    except (OSError, ValueError, subprocess.SubprocessError):
        sys.exit("backend_edge_health_failed")
