from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from config import Config

db = SQLAlchemy()
login_manager = LoginManager()

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)

    db.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = 'main.login'
    login_manager.login_message = 'Inloggen vereist om deze pagina te bekijken.'

    from app.models import User

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(int(user_id))

    from app.routes import bp as main_bp
    app.register_blueprint(main_bp)

    # Initialize database tables
    with app.app_context():
        # Create data directory if it doesn't exist
        import os
        db_path = app.config.get('SQLALCHEMY_DATABASE_URI', '')
        if db_path.startswith('sqlite:///'):
            db_file_path = db_path.replace('sqlite:///', '')
            db_dir = os.path.dirname(db_file_path)
            if db_dir and not os.path.exists(db_dir):
                os.makedirs(db_dir, exist_ok=True)
        
        db.create_all()

    return app
