"""
QQ机器人主入口
"""
import sys
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))


def _sqlite_supports_trigram(sqlite_module) -> bool:
    conn = None
    try:
        conn = sqlite_module.connect(":memory:")
        conn.execute("create virtual table t using fts5(content, tokenize='trigram')")
        return True
    except Exception:
        return False
    finally:
        if conn is not None:
            conn.close()


def _ensure_sqlite_for_chroma():
    """
    Ensure sqlite runtime supports FTS5 trigram tokenizer for Chroma.
    On some cloud images, system sqlite lacks trigram support.
    """
    try:
        import sqlite3
    except Exception:
        return

    if _sqlite_supports_trigram(sqlite3):
        return

    try:
        import pysqlite3
    except Exception as exc:
        print(
            "[WARN] sqlite3 does not support trigram tokenizer and pysqlite3 is unavailable: "
            f"{exc}"
        )
        print("[WARN] Chroma may fail and fallback to JSON storage.")
        return

    if _sqlite_supports_trigram(pysqlite3):
        sys.modules["sqlite3"] = pysqlite3
        print("[INFO] sqlite3 switched to pysqlite3 for Chroma trigram support.")
    else:
        print("[WARN] pysqlite3 is installed but still lacks trigram tokenizer support.")
        print("[WARN] Chroma may fail and fallback to JSON storage.")


_ensure_sqlite_for_chroma()

from src.core.bot import MyClient, build_intents
from src.core.config import Config
from src.utils.logger import setup_logger


def main():
    """主函数"""
    # 设置日志
    logger = setup_logger()
    
    try:
        # 验证配置
        Config.validate()
        logger.info("配置验证通过")
        
        # 创建并启动机器人（最小权限，避免 4014 disallowed intents）
        logger.info("正在启动QQ机器人...")
        intents = build_intents()
        client = MyClient(intents=intents)
        client.run(appid=Config.BOT_APPID, secret=Config.BOT_SECRET)
        
    except ValueError as e:
        logger.error(f"配置错误: {e}")
        logger.error("请检查 .env 文件配置")
        sys.exit(1)
    except Exception as e:
        logger.error(f"启动失败: {e}", exc_info=True)
        sys.exit(1)


if __name__ == "__main__":
    main()
