import sys
import base64
import os
from cryptography.hazmat.primitives.asymmetric import ed25519
from cryptography.hazmat.primitives import serialization

def main():
    print("\n" + "="*50)
    print(" ⛰️   VALLEYDAM IDENTITY GENERATOR")
    print("="*50)
    print("This tool will create a cryptographic identity for your AI Agent.\n")
    
    # 1. Get Domain
    domain = input("Enter your Agent's Domain (e.g., bot.mysite.com): ").strip()
    if not domain:
        print("❌ Error: Domain is required.")
        sys.exit(1)

    # 2. Generate Keys
    print(f"\nGenerating Ed25519 keypair for {domain}...")
    private_key = ed25519.Ed25519PrivateKey.generate()
    public_key = private_key.public_key()

    # 3. Save Private Key
    safe_name = domain.replace('.', '_')
    filename = f"{safe_name}_private.pem"
    
    if os.path.exists(filename):
        overwrite = input(f"⚠️  File {filename} exists. Overwrite? (y/N): ")
        if overwrite.lower() != 'y':
            print("Aborted.")
            sys.exit(0)

    private_bytes = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    )
    
    with open(filename, "wb") as f:
        f.write(private_bytes)

    # 4. Format Public Key for DNS
    public_bytes = public_key.public_bytes(
        encoding=serialization.Encoding.Raw,
        format=serialization.PublicFormat.Raw
    )
    public_b64 = base64.b64encode(public_bytes).decode('utf-8')

    # 5. Output Instructions
    print(f"\n✅ SUCCESS! Private key saved to: {os.path.abspath(filename)}")
    print("   (DO NOT share this file. Add it to your .gitignore)")
    
    print("\n🌍 === DNS SETUP INSTRUCTIONS ===")
    print(f"Log in to your DNS provider for '{domain}' and add this TXT record:\n")
    print(f"   Host:  _agent") 
    print(f"   Value: v=vd1; k=ed25519; p={public_b64};\n")
    print("="*50 + "\n")

if __name__ == "__main__":
    main()