# -*- coding: utf-8 -*-
import os
import sys
import logging
from app import create_app
from app.services.config import ConfigLoader
from config.settings import SystemConfig

# 禁用调试输出
ConfigLoader.debug_mode = False

# 加载系统配置
system_config = SystemConfig.load()

# 配置日志
if system_config.app.is_production:
    # 生产环境：禁用print输出到控制台
    # 将print重定向到日志系统
    class ProductionLogger:
        def __init__(self):
            self.logger = logging.getLogger('production')
            self.logger.setLevel(logging.INFO)

        def write(self, message):
            if message.strip():  # 忽略空行
                self.logger.info(message.strip())

        def flush(self):
            pass

    # 重定向stdout到日志（可选，如果想完全静默可以注释掉）
    # sys.stdout = ProductionLogger()

    # 配置日志格式
    handlers = []
    if system_config.logging.file:
        handlers.append(logging.FileHandler(system_config.logging.file))
    if system_config.logging.console:
        handlers.append(logging.StreamHandler(sys.stdout))
    
    logging.basicConfig(
        level=getattr(logging, system_config.logging.level),
        format=system_config.logging.format,
        handlers=handlers
    )

    # 禁用Flask/Werkzeug的HTTP请求日志
    log = logging.getLogger('werkzeug')
    log.setLevel(logging.ERROR)  # 只记录错误，不记录每个请求
else:
    # 开发环境：保留详细日志
    handlers = []
    if system_config.logging.file:
        handlers.append(logging.FileHandler(system_config.logging.file))
    if system_config.logging.console:
        handlers.append(logging.StreamHandler(sys.stdout))
    
    logging.basicConfig(
        level=getattr(logging, system_config.logging.level),
        format=system_config.logging.format,
        handlers=handlers if handlers else None
    )

app = create_app()

if __name__ == '__main__':
    # 从系统配置读取
    app_config = system_config.app
    
    if app_config.is_production:
        print(f"🚀 生产模式启动 - 监听 {app_config.host}:{app_config.port}")
        if system_config.logging.file:
            print(f"📝 日志输出到: {system_config.logging.file}")
    else:
        print(f"🔧 开发模式启动 - 监听 {app_config.host}:{app_config.port}")

    # 启动Flask服务器
    app.run(
        host=app_config.host,
        port=app_config.port,
        debug=False,
        threaded=app_config.threaded,
        use_reloader=app_config.use_reloader
    )