# Cortex Agent One-Liner Provisioner
import os
import sys
import urllib.request
import subprocess

print("🚀 Starting Cortex Agent Provisioning for node: {{ node_id }}")

# 1. Create .cortex/agent-node directory
install_dir = os.path.expanduser("~/.cortex/agent-node")
os.makedirs(install_dir, exist_ok=True)
os.chdir(install_dir)

# 2. Write agent_config.yaml
print("[*] Writing configuration...")
with open("agent_config.yaml", "w") as f:
    f.write("""{{ config_yaml }}""")

# 3. Download bootstrap_installer.py
installer_url = "{{ base_url }}/api/v1/agent/installer"
print(f"[*] Downloading installer from {installer_url} ...")
try:
    urllib.request.urlretrieve(installer_url, "bootstrap_installer.py")
except Exception as e:
    print(f"❌ Failed to download installer: {e}")
    sys.exit(1)

size = os.path.getsize("bootstrap_installer.py")
if size < 100:
    with open("bootstrap_installer.py") as f: content = f.read()
    print(f"❌ Downloaded file is too small or corrupt ({size} bytes): {content}")
    sys.exit(1)

# 4. Run installer with --daemon (or --non-interactive)
print("[*] Bootstrapping agent...")
cmd = [
    sys.executable, "bootstrap_installer.py", 
    "--daemon", 
    "--hub", "{{ base_url }}", 
    "--token", "{{ invite_token }}",
    "--node-id", "{{ node_id }}"
]
try:
    subprocess.run(cmd, check=True)
    print("✅ Provisioning complete! Node should be online in the Mesh Dashboard shortly.")
except subprocess.CalledProcessError as e:
    print(f"❌ Provisioning failed! Installer exited with code {e.returncode}")
    sys.exit(e.returncode)
except Exception as e:
    print(f"❌ Provisioning crashed: {e}")
    sys.exit(1)
