#!/usr/bin/env python3
"""
Startup script for the Wireframe Generator Backend
"""

import os
import sys
from pathlib import Path

def check_dependencies():
    """Check if required packages are installed"""
    try:
        import flask
        import anthropic
        import dotenv
        print("✅ All dependencies are installed")
        return True
    except ImportError as e:
        print(f"❌ Missing dependency: {e}")
        print("Please run: pip install -r requirements.txt")
        return False

def check_env_file():
    """Check if .env file exists and has API key"""
    env_path = Path(".env")
    if not env_path.exists():
        print("⚠️  No .env file found")
        print("Please copy env.example to .env and add your Claude API key")
        return False
    
    # Check if API key is set
    from dotenv import load_dotenv
    load_dotenv()
    
    api_key = os.getenv("CLAUDE_API_KEY")
    if not api_key or api_key == "your-claude-api-key-here":
        print("⚠️  Claude API key not configured")
        print("Please add your actual API key to the .env file")
        return False
    
    print("✅ Environment configured")
    return True

def main():
    """Main startup function"""
    print("🚀 Starting Wireframe Generator Backend...")
    
    # Check dependencies
    if not check_dependencies():
        sys.exit(1)
    
    # Check environment
    if not check_env_file():
        print("\nTo continue without API key (fallback mode), press Enter...")
        input()
    
    # Import and run the app
    try:
        from app import app
        port = int(os.environ.get('PORT', 5000))
        
        print(f"🌐 Backend starting on http://localhost:{port}")
        print("📱 Frontend can connect to this backend")
        print("🔄 Press Ctrl+C to stop the server")
        
        app.run(debug=True, host='0.0.0.0', port=port)
        
    except Exception as e:
        print(f"❌ Failed to start backend: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()
