#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
// PURPOSE: Founder's Tool to Cryptographically Seal the .env file.
// [Final Fortification: Sealed Environment]
"""

import sys
import os
import hashlib
from pathlib import Path
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding

# Define paths
SCRIPT_DIR = Path(__file__).resolve().parent
ROOT_DIR = SCRIPT_DIR.parent.parent.parent
ENV_FILE = ROOT_DIR / ".env"
SIG_FILE = ROOT_DIR / ".env.sig"

def seal_environment():
    print("=== PULSE ENVIRONMENT SEALER ===")

    # 1. Check for .env
    if not ENV_FILE.exists():
        print(f"ERROR: .env file not found at {ENV_FILE}")
        sys.exit(1)

    # 2. Get Private Key from user
    if len(sys.argv) > 1:
        priv_key_path_str = sys.argv[1]
    else:
        priv_key_path_str = input("Enter the full path to your Admin Private Key file: ")
    
    priv_key_path = Path(priv_key_path_str.strip())
    
    if not priv_key_path.exists():
        print("ERROR: Private key file not found.")
        sys.exit(1)

    try:
        with open(priv_key_path, "rb") as key_file:
            private_key = serialization.load_pem_private_key(
                key_file.read(),
                password=None,
            )
    except Exception as e:
        print(f"ERROR: Could not load private key. Ensure it's a valid PEM file. Details: {e}")
        sys.exit(1)

    # 3. Hash the .env content
    with open(ENV_FILE, "rb") as f:
        env_hash = hashlib.sha256(f.read()).hexdigest()

    # 4. Sign the hash
    signature = private_key.sign(
        env_hash.encode(),
        padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH
        ),
        hashes.SHA256()
    )

    # 5. Save signature
    with open(SIG_FILE, "w", encoding="utf-8") as f:
        f.write(signature.hex())

    print("\nSUCCESS!")
    print(f"Environment signature saved to: {SIG_FILE}")
    print("The PULSE Orchestrator will now verify this signature on boot.")

if __name__ == "__main__":
    seal_environment()
