#!/usr/bin/env python3
"""
alfred-pqc-vault v1.0 — NIST FIPS 203 (ML-KEM-1024) + FIPS 204 (ML-DSA-65)
Hybrid Post-Quantum Key Vault & Sovereign Dual-Signature Engine for Alfred Linux.

Cryptographic primitives (zero homemade crypto — 100% OpenSSL 3.5+ & NIST standards):
  • Vault Encryption: Hybrid X25519 + ML-KEM-1024 (FIPS 203) -> HKDF-SHA-256 -> AES-256-GCM (with AAD)
  • Sovereign Signing: Hybrid Ed25519 (RFC 8032) + ML-DSA-65 (FIPS 204) dual signatures
  • Honest Scope: Protects local key vaults, backups, files, receipts & agent certificates
    against Harvest-Now-Decrypt-Later and quantum forgery. Does not alter classical
    on-chain public-key signature schemes (e.g. secp256k1/Ed25519) of external blockchains.
"""
import argparse
import base64
import datetime
import hashlib
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.hkdf import HKDF

VAULT_VERSION = "alfred-pqc-vault-v1"
KEM_SUITE = "X25519+ML-KEM-1024+HKDF-SHA256+AES-256-GCM"
SIG_SUITE = "Ed25519+ML-DSA-65"
DEFAULT_DIR = os.path.expanduser("~/.local/share/alfred-pqc-vault")


def _run(cmd: list[str], cwd: str | None = None) -> subprocess.CompletedProcess:
    return subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)


def _check_openssl_pqc() -> str:
    r = _run(["openssl", "version"])
    if r.returncode != 0:
        raise RuntimeError("openssl binary not found")
    ver = r.stdout.strip()
    kems = _run(["openssl", "list", "-kem-algorithms"]).stdout
    sigs = _run(["openssl", "list", "-signature-algorithms"]).stdout
    if "ML-KEM-1024" not in kems or "ML-DSA-65" not in sigs:
        raise RuntimeError(f"OpenSSL lacks native ML-KEM-1024 / ML-DSA-65 support ({ver})")
    return ver


def _fingerprint(mlkem_pub: str, x25519_pub: str, mldsa_pub: str, ed25519_pub: str) -> str:
    h = hashlib.sha256()
    for part in (mlkem_pub, x25519_pub, mldsa_pub, ed25519_pub):
        h.update(part.strip().encode("utf-8"))
        h.update(b"\n|\n")
    return "alfred1pq" + h.hexdigest()[:32]


def _sign_id_fingerprint(mldsa_pub: str, ed25519_pub: str) -> str:
    h = hashlib.sha256()
    h.update(mldsa_pub.strip().encode("utf-8"))
    h.update(b"\n|\n")
    h.update(ed25519_pub.strip().encode("utf-8"))
    return "alfred1sig" + h.hexdigest()[:32]


def _gen_keypair(alg: str, priv_path: Path, pub_path: Path):
    r1 = _run(["openssl", "genpkey", "-algorithm", alg, "-out", str(priv_path)])
    if r1.returncode != 0:
        raise RuntimeError(f"genpkey {alg} failed: {r1.stderr.strip()}")
    os.chmod(priv_path, 0o600)
    r2 = _run(["openssl", "pkey", "-in", str(priv_path), "-pubout", "-out", str(pub_path)])
    if r2.returncode != 0:
        raise RuntimeError(f"pubout {alg} failed: {r2.stderr.strip()}")
    os.chmod(pub_path, 0o644)


def cmd_keygen(vdir: Path, force: bool = False) -> dict:
    ver = _check_openssl_pqc()
    vdir.mkdir(parents=True, exist_ok=True)
    os.chmod(vdir, 0o700)
    id_json = vdir / "identity.pub.json"
    if id_json.exists() and not force:
        raise RuntimeError(f"Identity already exists in {vdir} (pass --force to overwrite)")

    _gen_keypair("ML-KEM-1024", vdir / "kem_mlkem1024.priv.pem", vdir / "kem_mlkem1024.pub.pem")
    _gen_keypair("X25519", vdir / "kem_x25519.priv.pem", vdir / "kem_x25519.pub.pem")
    _gen_keypair("ML-DSA-65", vdir / "sig_mldsa65.priv.pem", vdir / "sig_mldsa65.pub.pem")
    _gen_keypair("ED25519", vdir / "sig_ed25519.priv.pem", vdir / "sig_ed25519.pub.pem")

    mlkem_pub = (vdir / "kem_mlkem1024.pub.pem").read_text(encoding="utf-8")
    x25519_pub = (vdir / "kem_x25519.pub.pem").read_text(encoding="utf-8")
    mldsa_pub = (vdir / "sig_mldsa65.pub.pem").read_text(encoding="utf-8")
    ed25519_pub = (vdir / "sig_ed25519.pub.pem").read_text(encoding="utf-8")

    vault_id = _fingerprint(mlkem_pub, x25519_pub, mldsa_pub, ed25519_pub)
    signer_id = _sign_id_fingerprint(mldsa_pub, ed25519_pub)
    pub_doc = {
        "version": VAULT_VERSION,
        "openssl": ver,
        "created_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(),
        "vault_id": vault_id,
        "signer_id": signer_id,
        "kem_suite": KEM_SUITE,
        "sig_suite": SIG_SUITE,
        "mlkem1024_pub_pem": mlkem_pub,
        "x25519_pub_pem": x25519_pub,
        "mldsa65_pub_pem": mldsa_pub,
        "ed25519_pub_pem": ed25519_pub,
    }
    id_json.write_text(json.dumps(pub_doc, indent=2) + "\n", encoding="utf-8")
    os.chmod(id_json, 0o644)
    return {"ok": True, "vault_dir": str(vdir), "vault_id": vault_id, "signer_id": signer_id, "openssl": ver}


def _derive_aead_key(ss_pq: bytes, ss_cl: bytes, salt: bytes) -> bytes:
    hkdf = HKDF(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        info=f"{VAULT_VERSION}|{KEM_SUITE}".encode("utf-8"),
    )
    return hkdf.derive(ss_pq + ss_cl)


def _build_aad(header: dict) -> bytes:
    return json.dumps(header, sort_keys=True, separators=(",", ":")).encode("utf-8")


def cmd_seal(infile: Path, outfile: Path, pub_json: Path) -> dict:
    _check_openssl_pqc()
    pub = json.loads(pub_json.read_text(encoding="utf-8"))
    plaintext = infile.read_bytes()

    with tempfile.TemporaryDirectory(prefix="apqv_seal_") as td:
        tdp = Path(td)
        mlkem_pub_p = tdp / "mlkem.pub.pem"
        x25519_pub_p = tdp / "x25519.pub.pem"
        mlkem_pub_p.write_text(pub["mlkem1024_pub_pem"], encoding="utf-8")
        x25519_pub_p.write_text(pub["x25519_pub_pem"], encoding="utf-8")

        # 1. ML-KEM-1024 encapsulate
        ct_p = tdp / "mlkem.ct"
        ss_pq_p = tdp / "mlkem.ss"
        r = _run(["openssl", "pkeyutl", "-encap", "-pubin", "-inkey", str(mlkem_pub_p), "-out", str(ct_p), "-secret", str(ss_pq_p)])
        if r.returncode != 0:
            raise RuntimeError(f"ML-KEM-1024 encap failed: {r.stderr.strip()}")
        mlkem_ct = ct_p.read_bytes()
        ss_pq = ss_pq_p.read_bytes()

        # 2. Ephemeral X25519 ECDH
        eph_priv = tdp / "eph_x25519.priv.pem"
        eph_pub = tdp / "eph_x25519.pub.pem"
        _gen_keypair("X25519", eph_priv, eph_pub)
        ss_cl_p = tdp / "x25519.ss"
        r = _run(["openssl", "pkeyutl", "-derive", "-inkey", str(eph_priv), "-peerkey", str(x25519_pub_p), "-out", str(ss_cl_p)])
        if r.returncode != 0:
            raise RuntimeError(f"X25519 derive failed: {r.stderr.strip()}")
        ss_cl = ss_cl_p.read_bytes()
        eph_pub_pem = eph_pub.read_text(encoding="utf-8")

    salt = os.urandom(32)
    nonce = os.urandom(12)
    key = _derive_aead_key(ss_pq, ss_cl, salt)

    header = {
        "version": VAULT_VERSION,
        "suite": KEM_SUITE,
        "recipient_vault_id": pub["vault_id"],
        "salt_b64": base64.b64encode(salt).decode("ascii"),
        "nonce_b64": base64.b64encode(nonce).decode("ascii"),
        "ephemeral_x25519_pub_pem": eph_pub_pem,
        "mlkem1024_ct_b64": base64.b64encode(mlkem_ct).decode("ascii"),
    }
    aad = _build_aad(header)
    ct = AESGCM(key).encrypt(nonce, plaintext, aad)

    envelope = dict(header)
    envelope["ciphertext_b64"] = base64.b64encode(ct).decode("ascii")
    outfile.write_text(json.dumps(envelope, indent=2) + "\n", encoding="utf-8")
    return {
        "ok": True,
        "outfile": str(outfile),
        "recipient_vault_id": pub["vault_id"],
        "suite": KEM_SUITE,
        "mlkem1024_ct_bytes": len(mlkem_ct),
        "plaintext_bytes": len(plaintext),
        "ciphertext_bytes": len(ct),
    }


def cmd_unseal(infile: Path, outfile: Path, vdir: Path) -> dict:
    _check_openssl_pqc()
    env = json.loads(infile.read_text(encoding="utf-8"))
    header = {k: env[k] for k in ("version", "suite", "recipient_vault_id", "salt_b64", "nonce_b64", "ephemeral_x25519_pub_pem", "mlkem1024_ct_b64")}
    if header["version"] != VAULT_VERSION or header["suite"] != KEM_SUITE:
        raise RuntimeError("Unsupported vault envelope version or suite")

    salt = base64.b64decode(header["salt_b64"])
    nonce = base64.b64decode(header["nonce_b64"])
    mlkem_ct = base64.b64decode(header["mlkem1024_ct_b64"])
    ct = base64.b64decode(env["ciphertext_b64"])

    with tempfile.TemporaryDirectory(prefix="apqv_unseal_") as td:
        tdp = Path(td)
        ct_p = tdp / "mlkem.ct"
        ss_pq_p = tdp / "mlkem.ss"
        ct_p.write_bytes(mlkem_ct)
        r = _run(["openssl", "pkeyutl", "-decap", "-inkey", str(vdir / "kem_mlkem1024.priv.pem"), "-in", str(ct_p), "-out", str(ss_pq_p)])
        if r.returncode != 0:
            raise RuntimeError(f"ML-KEM-1024 decap failed: {r.stderr.strip()}")
        ss_pq = ss_pq_p.read_bytes()

        eph_pub_p = tdp / "eph.pub.pem"
        eph_pub_p.write_text(header["ephemeral_x25519_pub_pem"], encoding="utf-8")
        ss_cl_p = tdp / "x25519.ss"
        r = _run(["openssl", "pkeyutl", "-derive", "-inkey", str(vdir / "kem_x25519.priv.pem"), "-peerkey", str(eph_pub_p), "-out", str(ss_cl_p)])
        if r.returncode != 0:
            raise RuntimeError(f"X25519 derive failed: {r.stderr.strip()}")
        ss_cl = ss_cl_p.read_bytes()

    key = _derive_aead_key(ss_pq, ss_cl, salt)
    aad = _build_aad(header)
    pt = AESGCM(key).decrypt(nonce, ct, aad)
    outfile.write_bytes(pt)
    os.chmod(outfile, 0o600)
    return {"ok": True, "outfile": str(outfile), "plaintext_bytes": len(pt), "suite": KEM_SUITE}


def _canonical_sign_manifest(file_sha256: str, file_size: int, signer_id: str, signed_utc: str, note: str) -> bytes:
    obj = {
        "version": VAULT_VERSION,
        "sig_suite": SIG_SUITE,
        "file_sha256": file_sha256,
        "file_size": file_size,
        "signer_id": signer_id,
        "signed_utc": signed_utc,
        "note": note,
    }
    return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode("utf-8")


def cmd_sign(infile: Path, sigfile: Path, vdir: Path, note: str = "") -> dict:
    _check_openssl_pqc()
    data = infile.read_bytes()
    file_sha = hashlib.sha256(data).hexdigest()
    mldsa_pub = (vdir / "sig_mldsa65.pub.pem").read_text(encoding="utf-8")
    ed25519_pub = (vdir / "sig_ed25519.pub.pem").read_text(encoding="utf-8")
    signer_id = _sign_id_fingerprint(mldsa_pub, ed25519_pub)
    signed_utc = datetime.datetime.now(datetime.timezone.utc).isoformat()
    manifest_bytes = _canonical_sign_manifest(file_sha, len(data), signer_id, signed_utc, note)

    with tempfile.TemporaryDirectory(prefix="apqv_sign_") as td:
        tdp = Path(td)
        mp = tdp / "manifest.bin"
        mp.write_bytes(manifest_bytes)
        ed_sig_p = tdp / "ed.sig"
        pq_sig_p = tdp / "pq.sig"

        r1 = _run(["openssl", "pkeyutl", "-sign", "-inkey", str(vdir / "sig_ed25519.priv.pem"), "-rawin", "-in", str(mp), "-out", str(ed_sig_p)])
        if r1.returncode != 0:
            raise RuntimeError(f"Ed25519 sign failed: {r1.stderr.strip()}")
        r2 = _run(["openssl", "pkeyutl", "-sign", "-inkey", str(vdir / "sig_mldsa65.priv.pem"), "-rawin", "-in", str(mp), "-out", str(pq_sig_p)])
        if r2.returncode != 0:
            raise RuntimeError(f"ML-DSA-65 sign failed: {r2.stderr.strip()}")

        ed_sig = ed_sig_p.read_bytes()
        pq_sig = pq_sig_p.read_bytes()

    doc = {
        "version": VAULT_VERSION,
        "sig_suite": SIG_SUITE,
        "file_name": infile.name,
        "file_sha256": file_sha,
        "file_size": len(data),
        "signer_id": signer_id,
        "signed_utc": signed_utc,
        "note": note,
        "ed25519_pub_pem": ed25519_pub,
        "mldsa65_pub_pem": mldsa_pub,
        "ed25519_sig_b64": base64.b64encode(ed_sig).decode("ascii"),
        "mldsa65_sig_b64": base64.b64encode(pq_sig).decode("ascii"),
    }
    sigfile.write_text(json.dumps(doc, indent=2) + "\n", encoding="utf-8")
    return {
        "ok": True,
        "sigfile": str(sigfile),
        "signer_id": signer_id,
        "file_sha256": file_sha,
        "ed25519_sig_bytes": len(ed_sig),
        "mldsa65_sig_bytes": len(pq_sig),
    }


def cmd_verify(infile: Path, sigfile: Path, expected_id: str = "") -> dict:
    _check_openssl_pqc()
    doc = json.loads(sigfile.read_text(encoding="utf-8"))
    data = infile.read_bytes()
    actual_sha = hashlib.sha256(data).hexdigest()

    calc_signer_id = _sign_id_fingerprint(doc["mldsa65_pub_pem"], doc["ed25519_pub_pem"])
    if calc_signer_id != doc.get("signer_id"):
        return {"ok": False, "error": "signer_id does not match embedded public keys"}
    if expected_id and calc_signer_id != expected_id:
        return {"ok": False, "error": f"signer_id mismatch: got {calc_signer_id}, expected {expected_id}"}
    if actual_sha != doc.get("file_sha256") or len(data) != int(doc.get("file_size", -1)):
        return {"ok": False, "error": "file SHA-256 or size mismatch (file modified)"}

    manifest_bytes = _canonical_sign_manifest(
        doc["file_sha256"], int(doc["file_size"]), doc["signer_id"], doc["signed_utc"], doc.get("note", "")
    )
    ed_sig = base64.b64decode(doc["ed25519_sig_b64"])
    pq_sig = base64.b64decode(doc["mldsa65_sig_b64"])

    with tempfile.TemporaryDirectory(prefix="apqv_ver_") as td:
        tdp = Path(td)
        mp = tdp / "manifest.bin"
        mp.write_bytes(manifest_bytes)
        ed_pub_p = tdp / "ed.pub.pem"
        pq_pub_p = tdp / "pq.pub.pem"
        ed_sig_p = tdp / "ed.sig"
        pq_sig_p = tdp / "pq.sig"
        ed_pub_p.write_text(doc["ed25519_pub_pem"], encoding="utf-8")
        pq_pub_p.write_text(doc["mldsa65_pub_pem"], encoding="utf-8")
        ed_sig_p.write_bytes(ed_sig)
        pq_sig_p.write_bytes(pq_sig)

        r1 = _run(["openssl", "pkeyutl", "-verify", "-pubin", "-inkey", str(ed_pub_p), "-rawin", "-in", str(mp), "-sigfile", str(ed_sig_p)])
        r2 = _run(["openssl", "pkeyutl", "-verify", "-pubin", "-inkey", str(pq_pub_p), "-rawin", "-in", str(mp), "-sigfile", str(pq_sig_p)])
        ed_ok = (r1.returncode == 0)
        pq_ok = (r2.returncode == 0)

    return {
        "ok": ed_ok and pq_ok,
        "signer_id": calc_signer_id,
        "file_sha256": actual_sha,
        "ed25519_verified": ed_ok,
        "mldsa65_verified": pq_ok,
        "sig_suite": SIG_SUITE,
        "signed_utc": doc["signed_utc"],
        "note": doc.get("note", ""),
    }


def cmd_self_test() -> dict:
    t0 = time.perf_counter()
    ver = _check_openssl_pqc()
    with tempfile.TemporaryDirectory(prefix="apqv_selftest_") as td:
        tdp = Path(td)
        vdir = tdp / "vault"
        kg = cmd_keygen(vdir, force=True)

        # 1. Seal & Unseal round-trip
        secret_in = tdp / "seed.txt"
        secret_in.write_text("SOVEREIGN_TEST_WALLET_ENTROPY_NIST_FIPS203_204\n", encoding="utf-8")
        sealed = tdp / "seed.apqv"
        unsealed = tdp / "seed.out.txt"
        seal_res = cmd_seal(secret_in, sealed, vdir / "identity.pub.json")
        cmd_unseal(sealed, unsealed, vdir)
        roundtrip_ok = (secret_in.read_bytes() == unsealed.read_bytes())

        # 2. 1-bit ciphertext tamper MUST fail
        env = json.loads(sealed.read_text(encoding="utf-8"))
        raw_ct = bytearray(base64.b64decode(env["ciphertext_b64"]))
        raw_ct[0] ^= 0x01
        env["ciphertext_b64"] = base64.b64encode(bytes(raw_ct)).decode("ascii")
        tampered_sealed = tdp / "seed_tampered.apqv"
        tampered_sealed.write_text(json.dumps(env), encoding="utf-8")
        vault_tamper_rejected = False
        try:
            cmd_unseal(tampered_sealed, tdp / "should_fail.txt", vdir)
        except Exception:
            vault_tamper_rejected = True

        # 3. Hybrid Ed25519 + ML-DSA-65 sign & verify
        sig_p = tdp / "seed.pqsig.json"
        sign_res = cmd_sign(secret_in, sig_p, vdir, note="NIST FIPS 203+204 Self-Test")
        ver_ok = cmd_verify(secret_in, sig_p, expected_id=kg["signer_id"])

        # 4. 1-bit payload tamper MUST fail
        bad_file = tdp / "seed_bad.txt"
        bad_file.write_text("SOVEREIGN_TEST_WALLET_ENTROPY_NIST_FIPS203_205\n", encoding="utf-8")
        ver_bad_file = cmd_verify(bad_file, sig_p)

        # 5. 1-bit ML-DSA-65 signature tamper MUST fail even while Ed25519 stays valid!
        sdoc = json.loads(sig_p.read_text(encoding="utf-8"))
        pq_b = bytearray(base64.b64decode(sdoc["mldsa65_sig_b64"]))
        pq_b[10] ^= 0x01
        sdoc["mldsa65_sig_b64"] = base64.b64encode(bytes(pq_b)).decode("ascii")
        bad_sig_p = tdp / "seed_bad_pq.pqsig.json"
        bad_sig_p.write_text(json.dumps(sdoc), encoding="utf-8")
        ver_bad_pq = cmd_verify(secret_in, bad_sig_p)

    elapsed_ms = round((time.perf_counter() - t0) * 1000, 1)
    all_ok = (
        roundtrip_ok
        and vault_tamper_rejected
        and ver_ok["ok"]
        and (not ver_bad_file["ok"])
        and (not ver_bad_pq["ok"])
        and ver_bad_pq.get("ed25519_verified") is True
        and ver_bad_pq.get("mldsa65_verified") is False
    )
    return {
        "ok": all_ok,
        "openssl": ver,
        "kem_suite": KEM_SUITE,
        "sig_suite": SIG_SUITE,
        "mlkem1024_ct_bytes": seal_res["mlkem1024_ct_bytes"],
        "ed25519_sig_bytes": sign_res["ed25519_sig_bytes"],
        "mldsa65_sig_bytes": sign_res["mldsa65_sig_bytes"],
        "checks": {
            "hybrid_vault_seal_unseal_exact": roundtrip_ok,
            "hybrid_vault_1bit_tamper_rejected": vault_tamper_rejected,
            "hybrid_sign_verify_both_pass": ver_ok["ok"],
            "file_1bit_tamper_rejected": not ver_bad_file["ok"],
            "mldsa65_1bit_sig_tamper_rejected": (not ver_bad_pq["ok"]) and (ver_bad_pq.get("mldsa65_verified") is False),
        },
        "elapsed_ms": elapsed_ms,
    }


def main():
    ap = argparse.ArgumentParser(description="Alfred NIST FIPS 203/204 Hybrid Post-Quantum Vault & Signer")
    sub = ap.add_subparsers(dest="cmd", required=True)

    p_kg = sub.add_parser("keygen", help="Generate Hybrid ML-KEM-1024 + X25519 + ML-DSA-65 + Ed25519 identity")
    p_kg.add_argument("--dir", default=DEFAULT_DIR)
    p_kg.add_argument("--force", action="store_true")

    p_se = sub.add_parser("seal", help="Encrypt a file/keystore into a Hybrid X25519+ML-KEM-1024 AES-256-GCM .apqv vault")
    p_se.add_argument("infile")
    p_se.add_argument("outfile")
    p_se.add_argument("--pub", default="", help="Path to recipient identity.pub.json")
    p_se.add_argument("--dir", default=DEFAULT_DIR)

    p_un = sub.add_parser("unseal", help="Decrypt a Hybrid .apqv vault file")
    p_un.add_argument("infile")
    p_un.add_argument("outfile")
    p_un.add_argument("--dir", default=DEFAULT_DIR)

    p_si = sub.add_parser("sign", help="Sign a file with Hybrid Ed25519 + ML-DSA-65 (FIPS 204)")
    p_si.add_argument("infile")
    p_si.add_argument("sigfile")
    p_si.add_argument("--dir", default=DEFAULT_DIR)
    p_si.add_argument("--note", default="")

    p_ve = sub.add_parser("verify", help="Verify a Hybrid Ed25519 + ML-DSA-65 signature envelope")
    p_ve.add_argument("infile")
    p_ve.add_argument("sigfile")
    p_ve.add_argument("--expected-id", default="")

    sub.add_parser("self-test", help="Run full empirical NIST FIPS 203/204 round-trip & tamper test suite")

    args = ap.parse_args()
    try:
        if args.cmd == "keygen":
            res = cmd_keygen(Path(args.dir), force=args.force)
        elif args.cmd == "seal":
            pub_p = Path(args.pub) if args.pub else (Path(args.dir) / "identity.pub.json")
            res = cmd_seal(Path(args.infile), Path(args.outfile), pub_p)
        elif args.cmd == "unseal":
            res = cmd_unseal(Path(args.infile), Path(args.outfile), Path(args.dir))
        elif args.cmd == "sign":
            res = cmd_sign(Path(args.infile), Path(args.sigfile), Path(args.dir), note=args.note)
        elif args.cmd == "verify":
            res = cmd_verify(Path(args.infile), Path(args.sigfile), expected_id=args.expected_id)
        elif args.cmd == "self-test":
            res = cmd_self_test()
        else:
            raise RuntimeError("Unknown command")
        print(json.dumps(res, indent=2))
        sys.exit(0 if res.get("ok") else 1)
    except Exception as exc:
        print(json.dumps({"ok": False, "error": str(exc)}, indent=2))
        sys.exit(1)


if __name__ == "__main__":
    main()
