import redis
import requests
import pymysql
from datetime import datetime

# ---------------- Redis 配置 ----------------
REDIS_HOST = "127.0.0.1"
REDIS_PORT = 6379
REDIS_DB = 7

# ---------------- MySQL 配置 ----------------
MYSQL_HOST = "127.0.0.1"
MYSQL_PORT = 25600
MYSQL_USER = "root"
MYSQL_PASS = "123456"
MYSQL_DB   = "pool"
TABLE_NAME = "`vipor.net`"

# ---------------- 连接 Redis ----------------
r = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB, decode_responses=True)

# ---------------- 连接 MySQL ----------------
conn = pymysql.connect(host=MYSQL_HOST, port=MYSQL_PORT, user=MYSQL_USER,
                       password=MYSQL_PASS, database=MYSQL_DB, charset='utf8mb4')
cursor = conn.cursor()

# ---------------- 从 Redis 获取矿池配置 ----------------
# 格式: pool_name:wallet:COIN:ALGORITHM
keys = r.keys("vipor.net:*")

def get_half_hour_time():
    """返回最近半点时间"""
    now = datetime.now()
    minute = 30 if now.minute >= 30 else 0
    return now.replace(minute=minute, second=0, microsecond=0)

def fetch_vipor_data(pool_name, coin, wallet, algorithm, api_pool):
    url = f"https://restapi.vipor.net/api/pools/{api_pool}/miners/{wallet}"
    try:
        resp = requests.get(url, timeout=10)
        resp.raise_for_status()
        data = resp.json()

        # 优先 performance.workers
        workers = data.get("performance", {}).get("workers")
        if not workers:
            workers = data.get("workers") or data.get("miners") or {}

        if not workers:
            print(f"{coin} | {api_pool} | {wallet} ⚠ 当前没有任何在线矿机")
            return

        for miner, info in workers.items():
            hashrate = info.get("hashrate", 0) or 0
            hashrate_mhs = hashrate / 1_000_000  # 转为 MH/s

            # 插入 MySQL
            sql = f"""INSERT INTO {TABLE_NAME} 
                (datetime, pool_name, wallet, miner, hashrate, coin, algorithm)
                VALUES (%s, %s, %s, %s, %s, %s, %s)"""
            cursor.execute(sql, (
                get_half_hour_time(),
                pool_name,   # 这里使用 Redis key 的第一部分
                wallet,
                miner,
                hashrate_mhs,
                coin,
                algorithm
            ))
            conn.commit()

            print(f"{coin} | {api_pool} | {miner}: {hashrate_mhs:.2f} MH/s 写入成功")

    except requests.exceptions.HTTPError as e:
        print(f"{coin} | {api_pool} | {wallet} 请求失败 HTTP 错误:", e)
    except Exception as e:
        print(f"{coin} | {api_pool} | {wallet} 请求失败:", e)


if __name__ == "__main__":
    for key in keys:
        parts = key.split(":")
        if len(parts) != 4:
            continue
        pool_name, wallet, coin, algorithm = parts

        # 构造普通和 solo pool 名（用于请求 API，不影响存入数据库的 pool_name）
        api_pools = []
        if coin == "NEXA":
            api_pools = ["nexa", "nexa_solo"]
        elif coin == "XEL":
            api_pools = ["xelis", "xelis_solo"]
        elif coin == "XNA":
            api_pools = ["neurai", "neurai_solo"]
        elif coin == "CLORE":
            api_pools = ["clore", "clore_solo"]
        else:
            api_pools = ["default", "default_solo"]

        for api_pool in api_pools:
            fetch_vipor_data(pool_name, coin, wallet, algorithm, api_pool)

# 关闭连接
cursor.close()
conn.close()