from flask import Flask
from flask_cors import CORS
from flask_jwt_extended import JWTManager
import logging
import os
from config.settings import config
from auth.jwt_auth import init_jwt

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


def create_app(config_name='default'):
    """Application factory pattern - creates and configures the Flask app"""
    # Get absolute paths for templates and static files
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    template_dir = os.path.join(base_dir, 'captchaScrapper', 'templates')
    static_dir = os.path.join(base_dir, 'captchaScrapper', 'static')
    
    app = Flask(__name__, 
                template_folder=template_dir,
                static_folder=static_dir)
    
    # Load configuration
    app.config.from_object(config[config_name])
    
    # Enable CORS
    CORS(app)
    
    # Initialize JWT
    init_jwt(app)
    
    # Ensure upload directory exists
    if not os.path.exists(app.config['UPLOAD_FOLDER']):
        os.makedirs(app.config['UPLOAD_FOLDER'])
    
    # Register blueprints
    from routes.health import health_bp
    from routes.csv_processor import csv_bp
    from routes.excel_routes import excel_bp
    from routes.auth_routes import auth_bp
    
    app.register_blueprint(health_bp)
    app.register_blueprint(csv_bp)
    app.register_blueprint(excel_bp)
    app.register_blueprint(auth_bp)
    
    # Register web UI routes
    from captchaScrapper.web_ui import register_web_ui_routes
    register_web_ui_routes(app)
    
    # Log app startup
    logger.info(f"Flask app created with config: {config_name}")
    
    return app 