#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
// PURPOSE: User-Controlled Admin Key Generator.
// [Step 1: The Key Ceremony]
// WARNING: This script handles sensitive cryptographic material.
"""

import sys
import json
import os
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
import datetime

# Define paths
SCRIPT_DIR = Path(__file__).resolve().parent
ROOT_DIR = SCRIPT_DIR.parent.parent.parent
AUTH_FILE = ROOT_DIR / "Corpus_Callosum" / "authorized_humans.json"

def generate_keys():
    print("=== PULSE ADMIN KEY CEREMONY ===")
    print("Generating secure RSA 2048 keypair...")

    # Generate private key
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
    )

    # Serialize private key (PEM format)
    pem_private = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    ).decode('utf-8')

    # Generate public key
    public_key = private_key.public_key()
    pem_public = public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
    ).decode('utf-8')

    # --- CRITICAL USER STEP ---
    print("\n" + "="*60)
    print("PRIVATE KEY - COPY THIS TO YOUR PASSWORD MANAGER NOW")
    print("="*60)
    print(pem_private)
    print("="*60)
    print("This key is NOT saved to disk. If you lose it, you lose Access.")
    print("="*60 + "\n")

    # Save public key to whitelist
    save_public_key(pem_public)

def save_public_key(pub_key_str):
    AUTH_FILE.parent.mkdir(parents=True, exist_ok=True)
    
    whitelist = {}
    if AUTH_FILE.exists():
        try:
            with open(AUTH_FILE, "r") as f:
                whitelist = json.load(f)
        except json.JSONDecodeError:
            pass

    # Add new key with a timestamp-based ID
    key_id = f"admin_{len(whitelist) + 1}"
    whitelist[key_id] = {
        "role": "FOUNDER",
        "public_key": pub_key_str,
        "added_at": str(datetime.datetime.now())
    }

    with open(AUTH_FILE, "w") as f:
        json.dump(whitelist, f, indent=2)
    
    print(f"Public Key saved to: {AUTH_FILE}")
    print(f"ID assigned: {key_id}")

if __name__ == "__main__":
    # Ensure cryptography lib is installed
    try:
        import cryptography
    except ImportError:
        print("Error: 'cryptography' library required. Run: pip install cryptography")
        sys.exit(1)
        
    generate_keys()