#!/usr/bin/env python3
"""
OpenAI API Key Setup Script for AuditWhizz AutoClicker
This script helps you set up your OpenAI API key for the supporting document analyzer.
"""

import os
import sys
from pathlib import Path

def setup_openai_key():
    """Interactive setup for OpenAI API key."""
    print("🔑 OpenAI API Key Setup for AuditWhizz AutoClicker")
    print("=" * 60)
    
    # Check if .env file exists
    env_file = Path(".env")
    if env_file.exists():
        print("✅ .env file already exists")
        with open(env_file, 'r') as f:
            content = f.read()
            if "OPENAI_API_KEY" in content:
                print("✅ OPENAI_API_KEY already configured in .env file")
                return
            else:
                print("⚠️  .env file exists but doesn't contain OPENAI_API_KEY")
    
    print("\n📋 To use the 'Analyze Docs' feature, you need an OpenAI API key.")
    print("   Get your API key from: https://platform.openai.com/api-keys")
    print("\n💡 You can set up your API key in several ways:")
    
    print("\n1️⃣  **Environment Variable (Recommended):**")
    print("   Windows (PowerShell):")
    print("   $env:OPENAI_API_KEY='your-api-key-here'")
    print("\n   Windows (Command Prompt):")
    print("   set OPENAI_API_KEY=your-api-key-here")
    print("\n   Linux/Mac:")
    print("   export OPENAI_API_KEY='your-api-key-here'")
    
    print("\n2️⃣  **Create .env file:**")
    print("   Create a .env file in the project root with:")
    print("   OPENAI_API_KEY=your-api-key-here")
    
    print("\n3️⃣  **Direct input (temporary):**")
    api_key = input("\n🔑 Enter your OpenAI API key (or press Enter to skip): ").strip()
    
    if api_key:
        if api_key.startswith(('sk-', 'sk-proj-')):
            # Create .env file
            env_content = f"OPENAI_API_KEY={api_key}\n"
            with open(env_file, 'w') as f:
                f.write(env_content)
            print("✅ .env file created with your API key!")
            print("⚠️  Note: This file contains sensitive information. Don't commit it to version control.")
        else:
            print("❌ Invalid API key format. API key should start with 'sk-' or 'sk-proj-'")
            return
    else:
        print("⏭️  Skipped API key setup. You can set it later using the methods above.")
    
    print("\n📚 **Next Steps:**")
    print("1. Restart your application after setting the API key")
    print("2. Test the 'Analyze Docs' button")
    print("3. Check logs/openai.log for any errors")
    
    print("\n🔒 **Security Note:**")
    print("   - Never commit your API key to version control")
    print("   - Use environment variables in production")
    print("   - Keep your .env file secure")

if __name__ == "__main__":
    setup_openai_key()
