#!/usr/bin/env python3
"""Configuration and setup script for the Wix Form Handler API
"""

import os
import secrets
import sys

# Add parent directory to path to import from src
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from alpine_bits_python.auth import generate_api_key


def generate_secure_keys():
    """Generate secure API keys for the application"""
    print("🔐 Generating Secure API Keys")
    print("=" * 50)

    # Generate API keys
    wix_api_key = generate_api_key()
    admin_api_key = generate_api_key()
    webhook_secret = secrets.token_urlsafe(32)

    print(f"🔑 Wix Webhook API Key: {wix_api_key}")
    print(f"🔐 Admin API Key: {admin_api_key}")
    print(f"🔒 Webhook Secret: {webhook_secret}")

    print("\n📋 Environment Variables")
    print("-" * 30)
    print(f"export WIX_API_KEY='{wix_api_key}'")
    print(f"export ADMIN_API_KEY='{admin_api_key}'")
    print(f"export WIX_WEBHOOK_SECRET='{webhook_secret}'")
    print("export REDIS_URL='redis://localhost:6379'  # Optional for production")

    print("\n🔧 .env File Content")
    print("-" * 20)
    print(f"WIX_API_KEY={wix_api_key}")
    print(f"ADMIN_API_KEY={admin_api_key}")
    print(f"WIX_WEBHOOK_SECRET={webhook_secret}")
    print("REDIS_URL=redis://localhost:6379")

    # Optionally write to .env file
    create_env = input("\n❓ Create .env file? (y/n): ").lower().strip()
    if create_env == "y":
        # Create .env in the project root (two levels up from scripts)
        env_path = os.path.join(
            os.path.dirname(os.path.dirname(os.path.dirname(__file__))), ".env"
        )
        with open(env_path, "w") as f:
            f.write(f"WIX_API_KEY={wix_api_key}\n")
            f.write(f"ADMIN_API_KEY={admin_api_key}\n")
            f.write(f"WIX_WEBHOOK_SECRET={webhook_secret}\n")
            f.write("REDIS_URL=redis://localhost:6379\n")
        print(f"✅ .env file created at {env_path}!")
        print("⚠️  Add .env to your .gitignore file!")

    print("\n🌐 Wix Configuration")
    print("-" * 20)
    print("1. In your Wix site, go to Settings > Webhooks")
    print("2. Add webhook URL: https://yourdomain.com/webhook/wix-form")
    print("3. Add custom header: Authorization: Bearer " + wix_api_key)
    print("4. Optionally configure webhook signature with the secret above")

    return {
        "wix_api_key": wix_api_key,
        "admin_api_key": admin_api_key,
        "webhook_secret": webhook_secret,
    }


def check_security_setup():
    """Check current security configuration"""
    print("🔍 Security Configuration Check")
    print("=" * 40)

    # Check environment variables
    wix_key = os.getenv("WIX_API_KEY")
    admin_key = os.getenv("ADMIN_API_KEY")
    webhook_secret = os.getenv("WIX_WEBHOOK_SECRET")
    redis_url = os.getenv("REDIS_URL")

    print("Environment Variables:")
    print(f"  WIX_API_KEY: {'✅ Set' if wix_key else '❌ Not set'}")
    print(f"  ADMIN_API_KEY: {'✅ Set' if admin_key else '❌ Not set'}")
    print(f"  WIX_WEBHOOK_SECRET: {'✅ Set' if webhook_secret else '❌ Not set'}")
    print(f"  REDIS_URL: {'✅ Set' if redis_url else '⚠️  Optional (using in-memory)'}")

    # Security recommendations
    print("\n🛡️  Security Recommendations:")
    if not wix_key:
        print("  ❌ Set WIX_API_KEY environment variable")
    elif len(wix_key) < 32:
        print("  ⚠️  WIX_API_KEY should be longer for better security")
    else:
        print("  ✅ WIX_API_KEY looks secure")

    if not admin_key:
        print("  ❌ Set ADMIN_API_KEY environment variable")
    elif wix_key and admin_key == wix_key:
        print("  ❌ Admin and Wix keys should be different")
    else:
        print("  ✅ ADMIN_API_KEY configured")

    if not webhook_secret:
        print("  ⚠️  Consider setting WIX_WEBHOOK_SECRET for signature validation")
    else:
        print("  ✅ Webhook signature validation enabled")

    print("\n🚀 Production Checklist:")
    print("  - Use HTTPS in production")
    print("  - Set up Redis for distributed rate limiting")
    print("  - Configure proper CORS origins")
    print("  - Set up monitoring and logging")
    print("  - Regular key rotation")


if __name__ == "__main__":
    print("🔐 Wix Form Handler API - Security Setup")
    print("=" * 50)

    choice = input(
        "Choose an option:\n1. Generate new API keys\n2. Check current setup\n\nEnter choice (1 or 2): "
    ).strip()

    if choice == "1":
        generate_secure_keys()
    elif choice == "2":
        check_security_setup()
    else:
        print("Invalid choice. Please run again and choose 1 or 2.")
