#
#  Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#

from api.utils.log_utils import init_root_logger
from plugin import GlobalPluginManager
init_root_logger("ragflow_server")

import logging
import os
import signal
import sys
import time
import traceback
import threading
import uuid
import argparse

import uvicorn

from api import settings
from api.db.runtime_config import RuntimeConfig
from api.db.services.document_service import DocumentService
from api import utils

from api.db.db_models import init_database_tables as init_web_db
from api.db.init_data import init_web_data
from api.versions import get_ragflow_version
from api.utils.configs import show_configs
from rag.settings import print_rag_settings
from rag.utils.mcp_tool_call_conn import shutdown_all_mcp_sessions
from rag.utils.redis_conn import RedisDistributedLock

# 全局停止事件
stop_event = threading.Event()

# 调试端口配置
RAGFLOW_DEBUGPY_LISTEN = int(os.environ.get('RAGFLOW_DEBUGPY_LISTEN', "0"))

def update_progress():
    """更新进度线程函数"""
    lock_value = str(uuid.uuid4())
    redis_lock = RedisDistributedLock("update_progress", lock_value=lock_value, timeout=60)
    logging.info(f"update_progress lock_value: {lock_value}")
    while not stop_event.is_set():
        try:
            if redis_lock.acquire():
                DocumentService.update_progress()
                redis_lock.release()
        except Exception:
            logging.exception("update_progress exception")
        finally:
            try:
                redis_lock.release()
            except Exception:
                logging.exception("update_progress exception")
            stop_event.wait(6)

def signal_handler(sig, frame):
    """信号处理器"""
    logging.info("Received interrupt signal, shutting down...")
    shutdown_all_mcp_sessions()
    stop_event.set()
    time.sleep(1)
    sys.exit(0)

def setup_health_check(app):
    """设置健康检查端点"""
    @app.get("/health")
    async def health_check():
        return {"status": "healthy", "version": get_ragflow_version()}

def main():
    """主函数"""
    logging.info(r"""
        _______   ______   _____    ______   _____ 
       |__   __| |  ____| |  __ \  |  ____| / ____|
          | |    | |__    | |__) | | |__    | (___ 
          | |    |  __|   |  _  /  |  __|    \___ \
          | |    | |____  | | \ \  | |____   ____) |
          |_|    |______| |_|  \_\ |______| |_____/ 

    """)
    logging.info(f'RAGFlow version: {get_ragflow_version()}')
    logging.info(f'project base: {utils.file_utils.get_project_base_directory()}')
    
    show_configs()
    settings.init_settings()
    print_rag_settings()

    # 调试模式配置
    if RAGFLOW_DEBUGPY_LISTEN > 0:
        logging.info(f"debugpy listen on {RAGFLOW_DEBUGPY_LISTEN}")
        try:
            import debugpy
            debugpy.listen(("0.0.0.0", RAGFLOW_DEBUGPY_LISTEN))
        except ImportError:
            logging.warning("debugpy not available, skipping debug setup")

    # 初始化数据库
    init_web_db()
    init_web_data()
    
    # 解析命令行参数
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--version", default=False, help="RAGFlow version", action="store_true"
    )
    parser.add_argument(
        "--debug", default=False, help="debug mode", action="store_true"
    )
    args = parser.parse_args()
    
    if args.version:
        print(get_ragflow_version())
        sys.exit(0)

    RuntimeConfig.DEBUG = args.debug
    if RuntimeConfig.DEBUG:
        logging.info("run on debug mode")

    RuntimeConfig.init_env()
    RuntimeConfig.init_config(JOB_SERVER_HOST=settings.HOST_IP, HTTP_PORT=settings.HOST_PORT)

    # 加载插件
    GlobalPluginManager.load_plugins()

    # 设置信号处理器
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    def delayed_start_update_progress():
        """延迟启动进度更新线程"""
        logging.info("Starting update_progress thread (delayed)")
        t = threading.Thread(target=update_progress, daemon=True)
        t.start()

    # 启动进度更新线程
    if RuntimeConfig.DEBUG:
        threading.Timer(1.0, delayed_start_update_progress).start()
    else:
        threading.Timer(1.0, delayed_start_update_progress).start()

    # 导入FastAPI应用
    from api.apps.__init___fastapi import app
    
    # 设置健康检查端点
    setup_health_check(app)

    # 启动HTTP服务器
    try:
        logging.info("RAGFlow HTTP server start...")
        uvicorn.run(
            app,
            host=settings.HOST_IP,
            port=settings.HOST_PORT,
            log_level="info" if not RuntimeConfig.DEBUG else "debug",
            reload=RuntimeConfig.DEBUG,
            access_log=True
        )
    except Exception:
        traceback.print_exc()
        stop_event.set()
        time.sleep(1)
        os.kill(os.getpid(), signal.SIGKILL)

if __name__ == '__main__':
    main()
