"""
Speakr 应用主模块

负责创建和配置 Flask 应用实例，初始化各层组件。
"""
import os
import logging
from flask import Flask, redirect, request
from werkzeug.middleware.proxy_fix import ProxyFix

from src.config import (
    LOG_LEVEL,
    get_app_config,
)
from src.logging_config import configure_logging
from src.flask_ext import init_extensions
from src.clients import init_database
from src.api import register_blueprints
from src.api.template_filters import register_template_filters
from src.services.register import init_services

logger = logging.getLogger(__name__)


class PrefixStripMiddleware:
    """Allow the app to serve routes hard-coded with a deployment prefix."""

    def __init__(self, app, prefix):
        self.app = app
        self.prefix = prefix.rstrip('/')

    def __call__(self, environ, start_response):
        path = environ.get('PATH_INFO', '')
        if path == self.prefix:
            environ['PATH_INFO'] = '/'
            environ['SCRIPT_NAME'] = self.prefix
        elif path.startswith(self.prefix + '/'):
            environ['PATH_INFO'] = path[len(self.prefix):] or '/'
            environ['SCRIPT_NAME'] = self.prefix
        return self.app(environ, start_response)


def create_app():
    """
    创建并配置 Flask 应用
    
    Returns:
        Flask: 配置完成的 Flask 应用实例
    """
    # 1. 配置日志
    configure_logging(LOG_LEVEL)
    
    # 2. 创建 Flask 应用实例
    app = Flask(
        __name__,
        template_folder='../templates',
        static_folder='../static'
    )
    
    # 3. 加载应用配置（所有配置由 config.py 统一管理，新增配置只需改 config.py）
    app.config.from_mapping(get_app_config())
    
    # 4. 配置反向代理支持（Nginx 等）
    app.wsgi_app = ProxyFix(
        app.wsgi_app,
        x_for=1,
        x_proto=1,
        x_host=1,
        x_prefix=1
    )
    app.wsgi_app = PrefixStripMiddleware(app.wsgi_app, '/tool/speakr')
    
    # 5. 初始化 Flask 扩展
    init_extensions(app)
    
    # 6. 初始化数据库
    init_database(app)
    
    # 7. 初始化分段服务和嵌入依赖检测（需要在蓝图注册前就绪）
    from src.services.register import init_early_services
    init_early_services(app)
    
    # 8. 注册蓝图
    register_blueprints(app)

    @app.before_request
    def redirect_root_to_prefixed_app():
        if request.path == '/' and not request.script_root:
            return redirect('/tool/speakr/', code=302)
    
    # 9. 注册模板过滤器
    register_template_filters(app)
    
    # 10. 初始化服务层（同步线程、文件监控、数据库迁移等）
    init_services(app)
    
    app.logger.info("Speakr 应用启动完成")
    
    return app


# 创建应用实例
app = create_app()


if __name__ == '__main__':
    # 开发环境启动（端口和 debug 模式从环境变量读取）
    port = int(os.environ.get('FLASK_PORT', '5000'))
    debug = os.environ.get('FLASK_DEBUG', 'false').lower() == 'true'
    app.run(host='0.0.0.0', port=port, debug=debug)
