"""Nod owner tool: approve your agents' requests from a terminal (stand-in until the phone app in M3).

The approval key is created and kept on this computer (~/.nod/owner.key by default). Nod only ever sees signatures.

    export NOD_OWNER_TOKEN=otk_...                 # from Nod when your company was onboarded
    python3 nod_owner.py init                  # create this device's key and register it (once)
    python3 nod_owner.py me                    # your company, agents, systems, pending count
    python3 nod_owner.py pending               # what your agents are asking for, with the other side's passport
    python3 nod_owner.py nod <nod_id>          # approve exactly that request
    python3 nod_owner.py decline <nod_id>
    python3 nod_owner.py new-agent <id> <name> <max_amount> [actions...]   # e.g. new-agent atlas Atlas 20000 "book freight"
    python3 nod_owner.py new-system <id> <name> [booking|receiving]
    python3 nod_owner.py rotate <agents|systems> <id>                       # new key, old one stops working
    python3 nod_owner.py approve-device <pubkey> [label]                    # approve your phone (shown in the app) from this device
    python3 nod_owner.py devices                                            # list your approval devices

Env: NOD_URL (default https://api.nodpass.org), NOD_OWNER_TOKEN, NOD_OWNER_KEY (key file path).
"""
import json, os, sys, urllib.error, urllib.request

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

# Self-contained on purpose: this one file (plus `pip install cryptography`) is what owners download from nodpass.org/docs.


class NodError(Exception):
    def __init__(self, code, msg):
        super().__init__(f"{code}: {msg}")
        self.code, self.msg = code, msg


def call(method, path, token=None, body=None, url=None):
    r = urllib.request.Request(url + path, method=method, data=json.dumps(body).encode() if body is not None else None)
    r.add_header("Content-Type", "application/json")
    r.add_header("User-Agent", "nod-owner-cli/0.2")
    if token:
        r.add_header("Authorization", "Bearer " + token)
    try:
        with urllib.request.urlopen(r, timeout=15) as resp:
            return json.loads(resp.read())
    except urllib.error.HTTPError as e:
        try:
            msg = json.loads(e.read()).get("error")
        except ValueError:
            msg = e.reason
        raise NodError(e.code, msg)


def decision_message(nod_id, binding, decision):
    # must match the Nod server exactly
    return json.dumps({"nod": nod_id, "binding": binding, "decision": decision}, sort_keys=True, separators=(",", ":")).encode()


class OwnerDevice:
    """This computer as the owner's approval device: the private key never leaves it."""

    def __init__(self, key_path):
        if os.path.exists(key_path):
            self.key = serialization.load_pem_private_key(open(key_path, "rb").read(), None)
        else:
            self.key = Ed25519PrivateKey.generate()
            fd = os.open(key_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
            with os.fdopen(fd, "wb") as f:
                f.write(self.key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))

    @property
    def pubkey(self):
        return self.key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()

    def sign(self, nod_id, binding, decision):
        return self.key.sign(decision_message(nod_id, binding, decision)).hex()

URL = os.environ.get("NOD_URL", "https://api.nodpass.org").rstrip("/")
TOKEN = os.environ.get("NOD_OWNER_TOKEN", "")
KEY = os.path.expanduser(os.environ.get("NOD_OWNER_KEY", "~/.nod/owner.key"))


def api(method, path, body=None):
    return call(method, "/v1" + path, TOKEN, body, url=URL)


def device():
    os.makedirs(os.path.dirname(KEY), mode=0o700, exist_ok=True)
    return OwnerDevice(KEY)


def show_pending():
    rows = api("GET", "/owner/pending")
    if not rows:
        print("Nothing waiting for your nod.")
        return
    for n in rows:
        p = call("GET", f"/v1/passports/{n['counterparty']}", url=URL)
        poa, pop = p["proof_of_authority"], p["proof_of_performance"]
        print(f"\n{n['id']}  {n['agent']} wants to {n['action']} with {n['counterparty']}")
        print(f"   amount {n['currency']} {n['amount']:,.2f}   ref {n['ref']}   reason: {n['reason']}")
        print(f"   {p['name']} acts for {poa['acts_for']} (owner verified: {'yes' if poa['owner_verified'] else 'NO'}), "
              f"{pop['confirmed_jobs']} confirmed jobs, {pop['disputes']} disputes")
        print(f"   expires {n['expires']}")
    print("\nApprove with:  python3 nod_owner.py nod <id>    or decline <id>")


def decide(nid, decision):
    n = [x for x in api("GET", "/owner/pending") if x["id"] == nid]
    if not n:
        sys.exit(f"{nid} isn't waiting for you (already decided, expired, or not yours).")
    n = n[0]
    sig = device().sign(n["id"], n["binding"], decision)
    r = api("POST", f"/nods/{nid}/decision", {"decision": decision, "signature": sig})
    print(f"{r['status']}: {n['agent']} → {n['counterparty']}, {n['currency']} {n['amount']:,.2f}, ref {n['ref']}")


def main(argv):
    if not argv or argv[0] in ("-h", "--help", "help"):
        print(__doc__)
        return
    if not TOKEN:
        sys.exit("Set NOD_OWNER_TOKEN to your owner key (otk_...).")
    cmd, args = argv[0], argv[1:]
    try:
        if cmd == "init":
            d = device()
            me = api("GET", "/owner")
            if me["device_registered"]:
                print(f"A device is already registered for {me['org']}. Key file here: {KEY}")
                return
            api("POST", "/owner/device", {"pubkey": d.pubkey})
            print(f"Registered this computer as {me['name']}'s approval device for {me['org']}.\nKey file: {KEY} (keep it safe; back it up)")
        elif cmd == "me":
            print(json.dumps(api("GET", "/owner"), indent=2))
        elif cmd == "pending":
            show_pending()
        elif cmd in ("nod", "decline") and len(args) == 1:
            decide(args[0], "nodded" if cmd == "nod" else "declined")
        elif cmd == "new-agent" and len(args) >= 3:
            auth = {"actions": args[3:] or ["book freight"], "max_amount": float(args[2]), "currency": "GBP"}
            r = api("POST", "/agents", {"agent_id": args[0], "name": args[1], "framework": "", "authority": auth})
            print(f"Agent {r['agent_id']} created. Its key (shown once, give it to the agent): {r['token']}")
        elif cmd == "new-system" and len(args) >= 2:
            r = api("POST", "/systems", {"system_id": args[0], "name": args[1], "kind": args[2] if len(args) > 2 else "booking"})
            print(f"System {r['system_id']} created. Its key (shown once): {r['token']}")
        elif cmd == "approve-device" and len(args) >= 1:
            me = api("GET", "/owner")
            pk = args[0].strip().lower()
            msg = json.dumps({"add_device": pk, "owner": me["owner_id"]}, sort_keys=True, separators=(",", ":")).encode()
            sig = device().key.sign(msg).hex()
            r = api("POST", "/owner/devices", {"pubkey": pk, "label": " ".join(args[1:]) or "phone", "approval": sig})
            print("Device approved." if not r.get("already_registered") else "That device was already registered.")
        elif cmd == "devices":
            for d in api("GET", "/owner/devices"):
                print(f"{d['id']}  {d['label'] or '-':20} key {d['key_start']}…  added {d['created']}  {'REVOKED ' + d['revoked'] if d['revoked'] else 'active'}")
        elif cmd == "rotate" and len(args) == 2 and args[0] in ("agents", "systems"):
            r = api("POST", f"/{args[0]}/{args[1]}/rotate-key")
            print(f"New key for {args[1]} (old one no longer works): {r['token']}")
        else:
            print(__doc__)
    except NodError as e:
        sys.exit(f"Nod refused: {e.msg}")


if __name__ == "__main__":
    main(sys.argv[1:])
