"""Flask application factory."""
import os
from flask import Flask
from flask.globals import app_ctx
from flask_sqlalchemy import SQLAlchemy
from app.config import ProductionConfig

# Initialize extensions
db = SQLAlchemy()

def create_app(config_class=ProductionConfig):
    """Create and configure the Flask application."""
    # Get the base directory (project root)
    base_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    template_dir = os.path.join(base_dir, 'templates')
    static_dir = os.path.join(base_dir, 'static')
    
    app = Flask(__name__, 
                template_folder=template_dir,
                static_folder=static_dir)
    app.config.from_object(config_class)
    
    # Initialize extensions with app
    db.init_app(app)
    
    # Register blueprints
    from app.routes.user_routes import user_bp, api_bp, face_bp
    app.register_blueprint(user_bp)
    app.register_blueprint(api_bp)
    app.register_blueprint(face_bp)
    
    # Create database tables
    with app.app_context():
        db.create_all()
    
    return app

