#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time
from datetime import datetime

from aidso_geo.config.base_config import init_redis8
from aidso_geo.utils import bh_utils


redis_client = init_redis8()


def safe_int(value, default=0):
    try:
        if value is None:
            return default
        return int(value)
    except Exception:
        return default


def get_active_channels():
    """
    查询所有启用中的第三方 channel
    """
    sql = """
        select channel, daily_limit, total_limit
        from geo_third_token
        where status = 1
    """
    return bh_utils.query_data(sql) or []


def sync_third_usage_once():
    """
    每小时同步第三方 token 用量快照。

    读取：
    1. Redis hash third_geo_daily：field = channel + YYYYMMDD
    2. Redis hash third_geo_total：field = channel

    写入：
    geo_third_usage_snapshot
    """
    now = datetime.now()
    today_pt = now.strftime("%Y%m%d")
    sync_time = now.strftime("%Y-%m-%d %H:%M:%S")
    insertime = int(time.time())

    try:
        channels = get_active_channels()
        if not channels:
            logger.info(f"[{sync_time}] sync_third_usage_once 无启用中的 channel")
            return

        # 一次性拉 Redis hash，避免用户多时频繁 hget
        daily_map = redis_client.hgetall("third_geo_daily") or {}
        total_map = redis_client.hgetall("third_geo_total") or {}

        insert_rows = []

        for item in channels:
            channel = str(item.get("channel", "")).strip()
            if not channel:
                continue

            daily_limit = safe_int(item.get("daily_limit"), 0)
            total_limit = safe_int(item.get("total_limit"), 0)

            daily_key = f"{channel}{today_pt}"

            today_used = safe_int(daily_map.get(daily_key), 0)
            total_used = safe_int(total_map.get(channel), 0)

            insert_rows.append({
                "channel": channel,
                "pt": today_pt,
                "daily_limit": daily_limit,
                "total_limit": total_limit,
                "today_used": today_used,
                "total_used": total_used,
                "today_remain": max(daily_limit - today_used, 0),
                "total_remain": max(total_limit - total_used, 0),
                "sync_time": sync_time,
                "insertime": insertime
            })

        if not insert_rows:
            logger.info(f"[{sync_time}] sync_third_usage_once 无可写入数据")
            return

        ok = bh_utils.insert_data("geo_third_usage_snapshot", insert_rows)
        if ok:
            logger.info(f"[{sync_time}] sync_third_usage_once 同步成功 rows={len(insert_rows)}")
        else:
            logger.error(f"[{sync_time}] sync_third_usage_once 同步失败 rows={len(insert_rows)}")

    except Exception as e:
        logger.exception(f"[{sync_time}] sync_third_usage_once 执行异常: {e}")


if __name__ == '__main__':
    sync_third_usage_once()