import modal

from ..video import downloader_image, app, config, modal_kv_product_cache

with downloader_image.imports():
    import httpx
    from loguru import logger
    from datetime import datetime, timedelta, timezone
    from httpx import Timeout

    from BowongModalFunctions.models.web_model import LiveProduct, LiveProductCaches

    @app.function(max_containers=config.video_downloader_concurrency, timeout=130)
    @modal.concurrent(max_inputs=50)
    async def monitor_live_room_product_trigger(cookie: str, room_id: str, author_id: str) -> int:
        def get_product_list():
            with httpx.Client(timeout=Timeout(timeout=120)) as client:
                resp = client.get(
                    f'https://bowongai-{config.modal_environment}--{config.modal_app_name}-fastapi-webapp-tikhub.modal.run/douyin/web/fetch_live_room_product_result',
                    params={"cookie": cookie, "room_id": room_id, "author_id": author_id})
                resp.raise_for_status()
            if resp.status_code == 200:
                if resp.json()["data"]["total"] >= 0:
                    return 0, resp.json()["data"]["promotions"]
                elif resp.json()["data"]["total"] == -1:
                    # 直播结束
                    return 1, []
                elif resp.json()["data"]["total"] == -2:
                    # IP风控
                    return 2, []
            # 其他错误
            return 3, []

        try:
            logger.info(f"room_id {room_id} author_id {author_id} 触发监控商品...")
            is_live, product_list = get_product_list()
            if is_live == 1:
                logger.warning(f"room_id {room_id} author_id {author_id} 直播已结束, 停止监控商品, 删除缓存")
                modal_kv_product_cache.pop(room_id, raise_exception=False)
                modal_kv_product_cache.batch_remove_cloudflare_kv([room_id])
                return is_live
            elif is_live == 2:
                logger.warning(f"room_id {room_id} author_id {author_id} 获取商品出现风控")
                return is_live
            elif is_live == 3:
                logger.warning(f"room_id {room_id} author_id {author_id} 网络请求出现错误")
                return is_live
            last_cache = modal_kv_product_cache.get_cache(room_id)
            if last_cache is not None:
                for product in last_cache.product_list:
                    for new_product in product_list:
                        if product.title == new_product["title"]:
                            product_list.remove(new_product)
                if len(product_list) > 0:
                    logger.success(f"room_id {room_id} author_id {author_id} 检测到商品变化, 增量刷新缓存")
                    # 最新的插入在最前
                    for new_product in product_list[::-1]:
                        last_cache.product_list.insert(0, LiveProduct(title=new_product["title"],
                                                                      leaf_category=new_product["leaf_category"],
                                                                      shop_id=new_product["shop_id"],
                                                                      product_id=new_product["product_id"],
                                                                      cover=new_product["cover"],
                                                                      detail_url=new_product["detail_url"]))
            else:
                logger.success(f"room_id {room_id} author_id {author_id} 新建缓存")
                last_cache = LiveProductCaches(room_id=room_id, author_id=author_id, product_list=[
                    LiveProduct(title=new_product["title"],
                                leaf_category=new_product["leaf_category"],
                                shop_id=new_product["shop_id"],
                                product_id=new_product["product_id"],
                                cover=new_product["cover"],
                                detail_url=new_product["detail_url"]) for new_product in product_list])
            last_cache.update_time = datetime.now(timezone(timedelta(hours=8))).strftime("%Y-%m-%d %H:%M:%S")
            last_cache.count = len(last_cache.product_list)
            modal_kv_product_cache.set_cache(last_cache)
            modal_kv_product_cache.batch_update_cloudflare_kv({last_cache.room_id: last_cache.model_dump_json()})
            return is_live
        except Exception as e:
            logger.exception(f"room_id {room_id} author_id {author_id} 触发监控商品发生错误 {e}")
            return 4