#!/usr/bin/env python3
from pathlib import Path
import argparse,base64,json,os,subprocess,sys,time,urllib.request
ap=argparse.ArgumentParser(description="MMTNEXUS OPT v4.1 one-command customer GPU onboarding")
ap.add_argument("--node-id",required=True);ap.add_argument("--enroll-token",default=os.environ.get("MMT_OPT_ENROLL_TOKEN"))
ap.add_argument("--base-url",default="https://opt.mmtnexus.com");ap.add_argument("--lanes",default="0,1")
ap.add_argument("--root",default="/opt/mmtnexus-opt");ap.add_argument("--package-root",default=str(Path(__file__).resolve().parents[1]))
ap.add_argument("--dry-run",action="store_true");ap.add_argument("--skip-model-download",action="store_true")
a=ap.parse_args();root=Path(a.root);pkg=Path(a.package_root);lanes=[x.strip() for x in a.lanes.split(",") if x.strip()]
if not a.enroll_token and not a.dry_run: raise SystemExit("MMT_OPT_ENROLL_TOKEN or --enroll-token is required")
if a.dry_run:
    print(json.dumps({"status":"DRY_RUN_PASS","node_id":a.node_id,"base_url":a.base_url,"lanes":lanes,"steps":["gpu_detect","fresh_ed25519","runtime_install","dependency_install","model_assets","preflight","central_enrollment","systemd_start","signed_health","activate"]},indent=2));raise SystemExit(0)
if os.geteuid()!=0: raise SystemExit("run as root")
subprocess.run(["nvidia-smi"],check=True,stdout=subprocess.DEVNULL)
(root/"runtime").mkdir(parents=True,exist_ok=True);(root/"assets").mkdir(parents=True,exist_ok=True);(root/"identity").mkdir(parents=True,exist_ok=True)
for src in (pkg/"runtime").glob("*.py"): (root/"runtime"/src.name).write_bytes(src.read_bytes())
for src in (pkg/"assets").glob("*"):
    if src.is_file():(root/"assets"/src.name).write_bytes(src.read_bytes())
venv=root/"venv";subprocess.run([sys.executable,"-m","venv",str(venv)],check=True)
subprocess.run([str(venv/"bin/pip"),"install","--disable-pip-version-check","requests","cryptography","torch","transformers","sentence-transformers"],check=True)
keyp=root/"identity"/f"{a.node_id}-ed25519.pem"
if keyp.exists(): raise SystemExit("identity already exists; refusing to overwrite")
keygen="""from pathlib import Path
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives import serialization
import os,sys
p=Path(sys.argv[1]);k=Ed25519PrivateKey.generate();p.write_bytes(k.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()));os.chmod(p,0o600);print(k.public_key().public_bytes(serialization.Encoding.Raw,serialization.PublicFormat.Raw).hex())
"""
pub=subprocess.check_output([str(venv/"bin/python"),"-c",keygen,str(keyp)],text=True).strip()
conf={"schema":"MMTNEXUS_CUSTOMER_GPU_NODE_V4_1","node_id":a.node_id,"base_url":a.base_url,"key_path":str(keyp),"lanes":lanes,"profile_id":"semantic-business-kpi-qwen3b-corpus37-v1","generation_model":"Qwen/Qwen2.5-3B-Instruct","installed_at":time.time()}
(root/"node.json").write_text(json.dumps(conf,indent=2)+"\n")
if not a.skip_model_download:
    subprocess.run([str(venv/"bin/python"),"-c","from huggingface_hub import snapshot_download;snapshot_download('Qwen/Qwen2.5-3B-Instruct');snapshot_download('sentence-transformers/all-MiniLM-L6-v2')"],check=True)
env=os.environ.copy();env["PYTHONPATH"]=str(root/"runtime");env["MMT_OPT_ROOT"]=str(root)
p=subprocess.run([str(venv/"bin/python"),str(root/"runtime/preflight.py")],env=env)
if p.returncode: raise SystemExit("preflight failed; node remains inactive")
req=urllib.request.Request(a.base_url.rstrip("/")+"/customer/fabric/v1/nodes/enroll",data=json.dumps({"node_id":a.node_id,"public_key_hex":pub,"lanes":lanes,"profile_id":conf["profile_id"],"hardware_class":subprocess.check_output(["nvidia-smi","--query-gpu=name","--format=csv,noheader"],text=True).splitlines()[0].strip()}).encode(),headers={"content-type":"application/json","authorization":"Bearer "+a.enroll_token},method="POST")
try:
    with urllib.request.urlopen(req,timeout=20) as r: enroll=json.loads(r.read())
except Exception as e: raise SystemExit("central enrollment failed; node remains inactive: "+repr(e))
if str(enroll.get("status","")).upper() not in {"ENROLLED","APPROVED","ACTIVE"}: raise SystemExit("central enrollment did not approve node: "+json.dumps(enroll))
for src in (pkg/"systemd").glob("*"): Path("/etc/systemd/system",src.name).write_bytes(src.read_bytes())
subprocess.run(["systemctl","daemon-reload"],check=True)
for lane in lanes:
    subprocess.run(["systemctl","enable","--now",f"mmtnexus-opt-worker@{lane}.service"],check=True)
subprocess.run(["systemctl","enable","--now","mmtnexus-opt-telemetry.service"],check=True)
# Signed activation gate: telemetry and all enrolled lanes must be fresh before central ACTIVE.
time.sleep(8)
activate_body={"node":a.node_id,"preflight_ready":True}
raw=json.dumps(activate_body,separators=(",",":" )).encode();ts=str(time.time())
activate_sig=subprocess.check_output([str(venv/"bin/python"),"-c","""import base64,sys
from pathlib import Path
from cryptography.hazmat.primitives import serialization
k=serialization.load_pem_private_key(Path(sys.argv[1]).read_bytes(),password=None);print(base64.b64encode(k.sign(sys.argv[2].encode()+b"\n"+sys.stdin.buffer.read())).decode())
""",str(keyp),ts],input=raw).decode().strip()
req2=urllib.request.Request(a.base_url.rstrip("/")+"/customer/fabric/v1/nodes/activate",data=raw,headers={"content-type":"application/json","x-mmt-node":a.node_id,"x-mmt-ts":ts,"x-mmt-signature":activate_sig},method="POST")
try:
    with urllib.request.urlopen(req2,timeout=20) as r: active=json.loads(r.read())
except Exception as e: raise SystemExit("signed activation failed; node remains ENROLLED/DRAINING: "+repr(e))
if str(active.get("status","")).upper()!="ACTIVE": raise SystemExit("central ACTIVE gate did not pass: "+json.dumps(active))
print(json.dumps({"status":"ONBOARDING_COMPLETE_ACTIVE","node_id":a.node_id,"lanes":lanes,"enrollment":enroll,"activation":active},indent=2))
