"""deliver.py - one command: a client record in, a live audited site out.

    python3 -m orchestrator.deliver demo-finger-lakes --dry-run
    python3 -m orchestrator.deliver demo-finger-lakes

Reads clients/<slug>.json, renders the bundle with site_renderer, stages it in
sites/<slug>/, publishes it to a per-client Cloudflare Pages project, fetches
the live URL back to confirm the business name is on the page, then writes a
site.published row to the audit ledger.

Staging goes to sites/<slug>/, never dist/ - dist/ belongs to deploy.py, which
wipes and rebuilds it from the Flask app's own static assets.
"""
from __future__ import annotations

import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
CLIENTS = ROOT / "clients"
SITES = ROOT / "sites"
BRANCH = "main"

if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

import site_renderer  # noqa: E402

URL_RE = re.compile(r"https://[a-z0-9-]+\.[a-z0-9-]+\.pages\.dev", re.I)


def load_profile(slug):
    path = CLIENTS / ("%s.json" % slug)
    if not path.is_file():
        sys.exit("no client record at %s" % path)
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except ValueError as exc:
        sys.exit("client record is not valid JSON: %s" % exc)
    if not isinstance(data, dict):
        sys.exit("client record must be a JSON object")
    if not data.get("name"):
        sys.exit("client record needs a 'name'")
    return data


def stage(slug, profile):
    bundle = site_renderer.render_site(profile)
    out = SITES / slug
    if out.exists():
        shutil.rmtree(out)
    out.mkdir(parents=True)
    total = 0
    for name in sorted(bundle):
        body = bundle[name]
        size = len(body.encode("utf-8"))
        (out / name).write_text(body, encoding="utf-8")
        total += size
        print("  + %s (%d bytes)" % (name, size))
    print("\nstaged %d file(s), %d bytes into %s" % (len(bundle), total, out))
    return out, total


def _pick_url(text):
    urls = URL_RE.findall(text)
    if not urls:
        return None
    for line in text.splitlines():
        if "alias" in line.lower():
            found = URL_RE.findall(line)
            if found:
                return found[0]
    return urls[0]


def _project_exists(project, env):
    """True / False / None - None means the list call itself failed (unknown, not missing)."""
    proc = subprocess.run(
        ["npx", "--yes", "wrangler@4.168.0", "pages", "project", "list"],
        env=env, capture_output=True, text=True,
    )
    out = (proc.stdout or "") + (proc.stderr or "")
    if proc.returncode != 0:
        print(out)
        return None
    return project in out


def _ensure_project(project, env):
    """Create the Pages project non-interactively. Production branch MUST be BRANCH."""
    exists = _project_exists(project, env)
    if exists is True:
        return
    if exists is None:
        print("could not list Pages projects - attempting the deploy anyway")
        return
    print("\ncreating Pages project %r (production branch %s) ..." % (project, BRANCH))
    proc = subprocess.run(
        ["npx", "--yes", "wrangler@4.168.0", "pages", "project", "create",
         project, "--production-branch", BRANCH],
        env=env, capture_output=True, text=True,
    )
    out = (proc.stdout or "") + (proc.stderr or "")
    print(out)
    if proc.returncode != 0:
        low = out.lower()
        if any(w in low for w in ("already exists", "already taken", "duplicate", "conflict")):
            print("project already exists - continuing")
            return
        sys.exit("could not create Pages project %r - its output is above" % project)


def publish(folder, project):
    token = (os.environ.get("CLOUDFLARE_API_TOKEN")
             or os.environ.get("CF_API_TOKEN") or "").strip()
    if len(token) < 20:
        token = ""
    account = os.environ.get("CF_ACCOUNT_ID")
    env = os.environ.copy()
    env.pop("CF_API_TOKEN", None)
    if token:
        env["CLOUDFLARE_API_TOKEN"] = token
    else:
        env.pop("CLOUDFLARE_API_TOKEN", None)
    env["CLOUDFLARE_ACCOUNT_ID"] = account or "2162530e654c8ef616413f57f3caa76c"
    env["CI"] = "1"

    _ensure_project(project, env)

    cmd = [
        "npx", "--yes", "wrangler@4.168.0", "pages", "deploy", str(folder),
        "--project-name", project, "--branch", BRANCH, "--commit-dirty=true",
    ]
    print("\nRunning:", " ".join(cmd), "\n")
    proc = subprocess.run(cmd, env=env, capture_output=True, text=True)
    out = (proc.stdout or "") + (proc.stderr or "")
    print(out)
    if proc.returncode != 0:
        sys.exit("wrangler failed (exit %s) - its output is above" % proc.returncode)
    url = _pick_url(out)
    if not url:
        sys.exit("wrangler reported success but no *.pages.dev URL was in its output")
    return url


def _stable_url(url):
    """Cloudflare 403s automated fetches of per-deploy hash URLs.
    The stable <project>.pages.dev address always serves - check that."""
    from urllib.parse import urlsplit, urlunsplit
    parts = urlsplit(url)
    host = parts.hostname or ""
    bits = host.split(".")
    if len(bits) > 2 and len(bits[0]) == 8 and all(c in "0123456789abcdef" for c in bits[0]):
        host = ".".join(bits[1:])
    netloc = host if not parts.port else "%s:%d" % (host, parts.port)
    return urlunsplit((parts.scheme or "https", netloc, parts.path or "/", "", ""))


def _fetch(url):
    """curl, not urllib - Python's SSL stack throws SSLV3_ALERT_HANDSHAKE_FAILURE
    against Cloudflare on some macOS builds."""
    import subprocess
    proc = subprocess.run(
        ["curl", "-sS", "-L", "--max-time", "20",
         "-A", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
               "(KHTML, like Gecko) Chrome/120.0 Safari/537.36",
         "-w", "\n%{http_code}", url],
        capture_output=True, text=True,
    )
    body, _, code = proc.stdout.rpartition("\n")
    try:
        return int(code.strip()), body
    except ValueError:
        return 0, proc.stdout


def verify(url, name, attempts=4, delay=4):
    import time
    targets = [u for u in (_stable_url(url), url) if u]
    tried, last = [], "no attempt made"
    for u in targets:
        for i in range(attempts):
            status, body = _fetch(u)
            if status == 200 and name in body:
                return True, "200, name present (%s)" % u
            last = ("HTTP %s" % status) if status != 200 else "200 but the business name is not on the page"
            tried.append("%s -> %s" % (u, last))
            if i < attempts - 1:
                time.sleep(delay)
    return False, "%s [%s]" % (last, "; ".join(tried[-2:]))


def ledger(slug, url, profile, files):
    try:
        from orchestrator import audit
    except Exception as exc:
        print("ledger: skipped (%s: %s)" % (type(exc).__name__, exc))
        return None
    return audit.record(
        actor="deliver",
        action="site.published",
        subject_type="client_site",
        subject_id=slug,
        payload={
            "url": url,
            "business": profile.get("name"),
            "trade": profile.get("trade"),
            "files": files,
        },
    )


def main(argv=None):
    ap = argparse.ArgumentParser(
        prog="orchestrator.deliver",
        description="Render, publish, verify, and record one client site.",
    )
    ap.add_argument("slug", help="client record name, e.g. demo-finger-lakes")
    ap.add_argument("--project", default=None, help="Cloudflare Pages project (defaults to the slug)")
    ap.add_argument("--dry-run", action="store_true", help="stage only; publish nothing")
    args = ap.parse_args(argv)

    project = args.project or args.slug
    profile = load_profile(args.slug)
    print("client: %s (%s)" % (profile.get("name"), profile.get("trade") or "generic"))

    folder, total = stage(args.slug, profile)

    if args.dry_run:
        print("\nDry run - nothing published.")
        return 0

    url = publish(folder, project)
    print("\nlive: %s" % url)

    ok, detail = verify(url, str(profile.get("name")))
    print("verify: %s - %s" % ("OK" if ok else "FAILED", detail))
    if not ok:
        print("\nNot recording this deploy - the live page did not verify.")
        return 1

    row = ledger(args.slug, url, profile, total)
    if row:
        print("ledger: site.published (seq %s)" % row.get("seq"))
    print("\ndone: %s" % url)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
