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

db = SQLAlchemy()
login_manager = LoginManager()
mail = Mail()

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

    db.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)

    login_manager.login_view = 'admin.login'
    login_manager.login_message = 'Please log in to access this page.'
    login_manager.login_message_category = 'info'

    from app.routes import main
    from app.admin_routes import admin

    app.register_blueprint(main)
    app.register_blueprint(admin, url_prefix='/admin')

    with app.app_context():
        db.create_all()
        # Create default admin if not exists
        from app.models import Admin
        if not Admin.query.filter_by(username='admin').first():
            admin_user = Admin(username='admin', email='admin@aplusacademy.co.za')
            admin_user.set_password('admin123')  # Change in production
            db.session.add(admin_user)
            db.session.commit()


    # DEBUG: Print actual config values
    print("=== MAIL CONFIG ===")
    print(f"SERVER: {app.config.get('MAIL_SERVER')}")
    print(f"PORT: {app.config.get('MAIL_PORT')}")
    print(f"TLS: {app.config.get('MAIL_USE_TLS')}")
    print(f"USERNAME: {app.config.get('MAIL_USERNAME')}")
    print(f"PASSWORD SET: {bool(app.config.get('MAIL_PASSWORD'))}")
    print("===================")
    return app


from app import models
