from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_restx import Api
from app.utils.log_config import LogConfig

# 初始化扩展，但不绑定到应用实例
db = SQLAlchemy()
log_config = LogConfig()

def create_app(config_object=None):
    app = Flask(__name__, instance_relative_config=True)
    
    # 默认配置
    app.config['SECRET_KEY'] = 'a-very-secret-key'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./tasks.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    if config_object:
        app.config.from_object(config_object)

    # 初始化扩展
    db.init_app(app)
    log_config.init_app(app)

    # 创建 Flask-RESTX API 实例（加入全局 Bearer Token 安全定义以启用 Swagger Authorize 按钮）
    authorizations = {
        'BearerAuth': {
            'type': 'apiKey',
            'in': 'header',
            'name': 'Authorization',
            'description': '在此处输入: Bearer <token>'
        }
    }
    api = Api(
        app,
        version='1.0',
        title='Task API',
        description='A simple Task API with Spring MVC style layers',
        authorizations=authorizations,
        security='BearerAuth'
    )

    # 导入并注册控制器（命名空间）
    from app.controller import task_controller, auth_controller, lovelace_url_controller, user_room_controller
    api.add_namespace(task_controller.api, path='/api/v1/tasks')
    api.add_namespace(auth_controller.api, path='/api/v1/auth')
    api.add_namespace(lovelace_url_controller.api, path='/api/v1/lovelace')
    api.add_namespace(user_room_controller.api, path='/api/v1/user-room')

    # 注册全局错误处理器
    from app.utils.error_handler import register_error_handlers
    register_error_handlers(app)

    # 在应用上下文中创建数据库表
    with app.app_context():
        db.create_all()

    return app
