import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_mail import Mail
from flask_wtf.csrf import CSRFProtect
from flask_migrate import Migrate
from app.config import Config
from pydub import AudioSegment
from app.utils.filters import timeago, slugify

# Initialize Flask extensions
db = SQLAlchemy()
login_manager = LoginManager()
mail = Mail()
csrf = CSRFProtect()
migrate = Migrate()

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    # Set FFmpeg paths for pydub
    try:
        if os.path.exists(app.config['FFMPEG_PATH']):
            AudioSegment.converter = app.config['FFMPEG_PATH']
            AudioSegment.ffmpeg = app.config['FFMPEG_PATH']
            AudioSegment.ffprobe = app.config['FFPROBE_PATH']
            app.logger.info(f"FFmpeg configured successfully at {app.config['FFMPEG_PATH']}")
        else:
            app.logger.warning(f"FFmpeg not found at {app.config['FFMPEG_PATH']}. Audio features may not work correctly.")
            
            # Try to find ffmpeg in PATH
            import shutil
            ffmpeg_in_path = shutil.which('ffmpeg')
            if ffmpeg_in_path:
                app.logger.info(f"Found FFmpeg in PATH: {ffmpeg_in_path}")
                AudioSegment.converter = ffmpeg_in_path
                AudioSegment.ffmpeg = ffmpeg_in_path
                ffprobe_in_path = shutil.which('ffprobe')
                if ffprobe_in_path:
                    AudioSegment.ffprobe = ffprobe_in_path
    except Exception as e:
        app.logger.error(f"Error configuring FFmpeg: {str(e)}. Audio features may not work correctly.")

    # Initialize extensions with app
    db.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)
    # Initialize extensions
    csrf.init_app(app)
    migrate.init_app(app, db)

    # Configure login
    login_manager.login_view = 'auth.login'
    login_manager.login_message = 'Please log in to access this page.'
    login_manager.login_message_category = 'info'

    # Register Jinja filters
    import json
    app.jinja_env.filters['timeago'] = timeago
    app.jinja_env.filters['slugify'] = slugify
    app.jinja_env.filters['tojson'] = json.dumps
    app.jinja_env.filters['fromjson'] = json.loads
    # Add Python built-in functions
    app.jinja_env.globals['max'] = max
    from app.utils.text_processor import process_content
    app.jinja_env.filters['process_content'] = process_content

    # Import and register blueprints
    from app.routes.main import main_bp
    from app.routes.auth import auth_bp
    from app.routes.admin import admin_bp
    from app.routes.student import student_bp
    from app.routes.teacher import bp as teacher_bp  # Import the teacher blueprint as teacher_bp
    from app.routes.debug import bp as debug_bp  # Import the debug blueprint

    # Import student quiz routes to register them with the student blueprint
    from app.routes import student_quiz

    # Register blueprints with their URL prefixes
    app.register_blueprint(main_bp)  # No url_prefix for main routes
    app.register_blueprint(auth_bp, url_prefix='/auth')
    app.register_blueprint(admin_bp, url_prefix='/admin')
    app.register_blueprint(teacher_bp, url_prefix='/teacher')  # Using the imported bp as teacher_bp
    app.register_blueprint(student_bp, url_prefix='/student')
    app.register_blueprint(debug_bp, url_prefix='/debug')  # Register debug blueprint

    # Create database tables
    with app.app_context():
        db.create_all()

    @login_manager.user_loader
    def load_user(user_id):
        from app.models.user import User
        return User.query.get(int(user_id))

    return app
