"""Run a real precise-connect-verify binary on a synthetic loopback REST catalog."""
import argparse
import hashlib
import json
from pathlib import Path
import subprocess
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlsplit

CANARY = b"precise-public-connection-fixture-v1"
DENIED = {"archive", "billing", "restricted"}


class Catalog(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass

    def respond(self, status, body=b"", **headers):
        self.send_response(status)
        for k, v in headers.items():
            self.send_header(k, v)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        if self.command != "HEAD":
            self.wfile.write(body)

    def do_HEAD(self):
        self.do_GET()

    def do_GET(self):
        path = urlsplit(self.path).path
        origin = self.server.origin
        if path == "/objects/canary":
            etag = '"sample-object-1"'
            if self.command == "HEAD":
                return self.respond(200, CANARY, ETag=etag)
            if self.headers.get("If-Match") != etag or self.headers.get("Range") != f"bytes=0-{len(CANARY)-1}":
                return self.respond(412)
            return self.respond(206, CANARY, ETag=etag, **{"Content-Range": f"bytes 0-{len(CANARY)-1}/{len(CANARY)}"})
        if self.headers.get("Authorization") != "Bearer sample-local-reader":
            return self.respond(401)
        tables = "/v1/namespaces/demo/tables"
        if path == "/v1/config":
            data = {"defaults": {}, "overrides": {}, "endpoints": []}
        elif path == "/v1/namespaces":
            data = {"namespaces": [["demo"]]}
        elif path == tables:
            # The forbidden tables exist and are listed; only reading them is denied.
            data = {"identifiers": [{"namespace": ["demo"], "name": name} for name in ["delivery", *sorted(DENIED)]]}
        elif path.startswith(tables+"/") and path.split("/")[-1] in DENIED:
            return self.respond(403)
        elif path == tables+"/delivery":
            data = {"metadata-location": origin+"/objects/meta.json", "metadata": {
                "format-version": 2, "table-uuid": "4dae87ac-6966-4368-8ccd-7c73a677dec1", "location": origin+"/objects/delivery",
                "current-snapshot-id": 17, "current-schema-id": 1,
                "schemas": [{"schema-id": 1, "fields": [{"id": 1, "name": "impressions", "required": True, "type": "long"}]}],
                "snapshots": [{"snapshot-id": 17, "timestamp-ms": 1790000000000, "manifest-list": origin+"/objects/manifest-list.avro"}]}}
        else:
            return self.respond(404)
        self.respond(200, json.dumps(data).encode(), **{"Content-Type": "application/json", "ETag": '"demo-v1"'})


def execute(binary, inputs, output, use_grant_port):
    output.mkdir()
    # Keep the operator's credentials out of this synthetic run.
    origins = {grant["catalog_url"] for grant in inputs.values()}
    if len(origins) != 1:
        raise ValueError("the four published templates must share a loopback origin")
    location = urlsplit(origins.pop())
    if location.scheme != "http" or location.hostname != "127.0.0.1" or not location.port:
        raise ValueError("expected the published IPv4 loopback origin and port")
    port = location.port if use_grant_port else 0
    with ThreadingHTTPServer(("127.0.0.1", port), Catalog) as server, tempfile.TemporaryDirectory() as td:
        server.origin = "http://127.0.0.1:"+str(server.server_port)
        thread = threading.Thread(target=server.serve_forever, daemon=True)
        thread.start()
        try:
            private = Path(td)/"ephemeral.pk8"
            pub = output/"public-test-key.pem"
            subprocess.run(["openssl", "genpkey", "-algorithm", "RSA", "-pkeyopt", "rsa_keygen_bits:2048", "-out", private],
                           check=True, stderr=subprocess.DEVNULL)
            subprocess.run(["openssl", "pkey", "-in", private, "-pubout", "-out", pub], check=True)
            env = {"PRECISE_TOPOLOGY_SIGNING_KEY": private.read_text(), "DEMO_READER_TOKEN": "sample-local-reader"}
            cards = {}
            for cloud, template in inputs.items():
                # Only the loopback origin changes. Path and resource grants come from the download.
                origin = server.origin
                grant = {**template, "catalog_url": origin, "storage": {**template["storage"], "prefix": origin+"/objects"},
                         "verify": {**template["verify"], "storage_canary": origin+"/objects/canary"}}
                if use_grant_port and grant != template:
                    raise ValueError("recorded grant fields do not match the local listener")
                path = output/(cloud+"-connect-grant.json")
                path.write_text(json.dumps(grant, indent=2)+"\n")
                wire = subprocess.check_output([binary, path], env=env)
                signed = json.loads(wire)
                card_file = output/(cloud+"-card.json")
                card_file.write_bytes(wire)
                verified = json.loads(subprocess.check_output(
                    [binary, "--verify", pub, card_file, "--tenant", template["tenant"], "--max-age", "3600"], env={}))
                observed = verified["permissions"]
                if not (verified["verified"] and verified["tenant"] == template["tenant"] and verified["principal"] == template["principal"]
                        and verified["cloud"] == cloud and verified["relations"]["delivery"]["door"] == "plain_iceberg"):
                    raise ValueError("card differs from the expected grant")
                if len(observed) != 12 or sum(c["expected"] == "allow" and c["passed"] for c in observed) != 6 or sum(
                        c["expected"] == "forbid" and c["passed"] and c["observed"] == "403" for c in observed) != 6:
                    raise ValueError("permission observations differ from the provisioned catalog")
                # Independent scope binding for this template (only ASCII strings).
                normalized = {k: {"require_governance": False, "arrow_export": False, **v} for k,v in grant["relations"].items()}
                scope = ["precise.catalog-scope/v1",grant["tenant"],grant["principal"],cloud,origin,grant["warehouse"],normalized,origin+"/objects"]
                digest = "sha256:"+hashlib.sha256(json.dumps(scope,sort_keys=True,separators=(",",":")).encode()).hexdigest()
                if verified["scope"] != digest:
                    raise ValueError("scope does not match this invocation")
                cards[cloud] = signed
            (output/"signed-cards.json").write_text(json.dumps(cards, indent=2)+"\n")
            print("4 signed cards, 24 allowed observations, 24 denied observations, 4 expected scopes")
        finally:
            server.shutdown()
            thread.join()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("binary", type=Path)
    parser.add_argument("grants", type=Path)
    parser.add_argument("new_output_directory", type=Path)
    parser.add_argument("--use-grant-port", action="store_true", help="bind the published loopback port and replay every original grant field")
    args = parser.parse_args()
    execute(args.binary.resolve(), json.loads(args.grants.read_text()), args.new_output_directory, args.use_grant_port)
