# -*- coding:utf-8 -*-
"""
# Time       ：2023/12/8 18:23
# Author     ：Maxwell
# version    ：python 3.9
# Description：
"""

from typing import Callable
from fastapi import FastAPI
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from infoman.service.database.mysql import register_mysql
from infoman.config import config

import redis
from infoman.utils.log import logger
from qdrant_client import AsyncQdrantClient
from infoman.service.mq.nats.nats_client import NATSClient


def startup(app: FastAPI) -> Callable:
    async def app_start() -> None:
        await register_mysql(app)

        if len(config.NATS_SERVER_LIST) > 0:
            app.state.nats_client = NATSClient(
                config.NATS_SERVER_LIST, config.NATS_NAME
            )

        if config.QDRANT_HOST:
            app.state.qdrant_client = AsyncQdrantClient(
                port=config.QDRANT_HTTP_PORT,
                grpc_port=config.QDRANT_GRPC_PORT,
                api_key=config.QDRANT_API_KEY,
                host=config.QDRANT_HOST,
            )

        if config.REDIS_HOST and config.REDIS_PORT:
            redis_pool = redis.asyncio.ConnectionPool(
                host=config.REDIS_HOST,
                port=config.REDIS_PORT,
                db=config.REDIS_DB,
                password=config.REDIS_PASSWORD,
                encoding="utf-8",
                decode_responses=False,
                max_connections=30,
                retry_on_timeout=True,
                socket_timeout=4,
                socket_connect_timeout=2,
                health_check_interval=30,
            )
            app.state.redis_client = redis.asyncio.Redis(connection_pool=redis_pool)

            try:
                FastAPICache.init(
                    RedisBackend(app.state.redis_client),
                    prefix=f"{config.APP_NAME}({config.APP_VERSION})",  # 缓存key前缀
                )
                logger.info("✅ FastAPI Cache initialized with Redis")
            except Exception as e:
                logger.warning(
                    f"⚠️ FastAPI Cache init failed, cache will be disabled: {e}"
                )

    return app_start


def stopping(app: FastAPI) -> Callable:
    async def stop_app() -> None:
        if app.state.redis_client:
            await app.state.redis_client.close()

    return stop_app
