import hmac
import hashlib
import base64
import json
import time
import secrets
import string

def generate_secure_secret(length=64):
    """生成安全的随机十六进制字符串"""
    return secrets.token_hex(length // 2)

def generate_random_string(length=32):
    """生成包含字母数字的随机字符串 (用于密码等)"""
    chars = string.ascii_letters + string.digits
    return ''.join(secrets.choice(chars) for _ in range(length))

def base64url_encode(input_bytes):
    return base64.urlsafe_b64encode(input_bytes).decode('utf-8').rstrip('=')

def generate_jwt(role, secret):
    # 1. Header
    header = {
        "alg": "HS256",
        "typ": "JWT"
    }
    
    # 2. Payload
    now = int(time.time())
    payload = {
        "role": role,
        "iss": "supabase",
        "iat": now,
        "exp": now + 315360000  # 10年有效期
    }
    
    # Encode parts
    header_b64 = base64url_encode(json.dumps(header).encode('utf-8'))
    payload_b64 = base64url_encode(json.dumps(payload).encode('utf-8'))
    
    # 3. Signature
    signing_input = f"{header_b64}.{payload_b64}".encode('utf-8')
    signature = hmac.new(
        secret.encode('utf-8'),
        signing_input,
        hashlib.sha256
    ).digest()
    signature_b64 = base64url_encode(signature)
    
    return f"{header_b64}.{payload_b64}.{signature_b64}"

if __name__ == "__main__":
    print("=" * 60)
    print("🔐 Supabase 全自动配置生成器 (Zero Dependency)")
    print("=" * 60)
    print("正在生成所有密钥...\n")
    
    # 1. 自动生成主密钥
    jwt_secret = generate_secure_secret(64)
    
    # 2. 基于主密钥生成 JWT
    anon_key = generate_jwt("anon", jwt_secret)
    service_key = generate_jwt("service_role", jwt_secret)
    
    # 3. 生成其他加密 Key和密码
    vault_key = generate_secure_secret(32)
    meta_key = generate_secure_secret(32)
    secret_key_base = generate_secure_secret(64)
    
    db_password = generate_random_string(20)
    dashboard_password = generate_random_string(16)
    
    # 4. 输出结果
    print(f"✅ 生成完成！请直接复制以下内容覆盖您的 .env 文件中的对应部分：\n")
    
    print("-" * 20 + " [ 复制开始 ] " + "-" * 20)
    print(f"# === 数据库安全配置 ===")
    print(f"POSTGRES_PASSWORD={db_password}")
    print(f"JWT_SECRET={jwt_secret}")
    print(f"ANON_KEY={anon_key}")
    print(f"SERVICE_ROLE_KEY={service_key}")
    print(f"SECRET_KEY_BASE={secret_key_base}")
    print(f"VAULT_ENC_KEY={vault_key}")
    print(f"PG_META_CRYPTO_KEY={meta_key}")
    print(f"\n# === 管理后台配置 ===")
    print(f"DASHBOARD_USERNAME=admin")
    print(f"DASHBOARD_PASSWORD={dashboard_password}")
    print("-" * 20 + " [ 复制结束 ] " + "-" * 20)
    
    print("\n💡 提示：")
    print(f"1. 数据库密码: {db_password}")
    print(f"2. 后台登录密码: {dashboard_password}")
    print("请妥善保管这些密码！")
