from ahserver.serverenv import ServerEnv
from ahserver.configuredServer import ConfiguredServer
from ahserver.webapp import webapp
from appPublic.worker import awaitify
from query import search_query
from embed import embed
from deletefile import delete_document
import logging
import os

# 配置日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(os.path.expanduser('~/rag/logs/rag.log'), encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)


def get_module_dbname(name):
    """
    获取默认数据库名称，优先使用环境变量 RAG_DB_TYPE，未设置时返回 'textdb'。
    """
    return os.getenv('RAG_DB_TYPE', 'textdb')


def init():
    """
    初始化 RAG 系统，绑定核心函数到 ServerEnv。
    """
    try:
        logger.info("初始化 RAG 系统")
        g = ServerEnv()

        # 绑定核心函数为异步版本
        g.embed = awaitify(embed)
        g.query = awaitify(search_query)
        g.delete = awaitify(delete_document)
        g.get_module_dbname = get_module_dbname

        logger.info("RAG 系统初始化完成")
        return g
    except Exception as e:
        logger.error(f"初始化失败: {str(e)}")
        raise


if __name__ == '__main__':
    logger.info("启动 RAG Web 服务器")
    webapp(init)