import redis
import requests
import pymysql
from datetime import datetime, timedelta

# ---------------- 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 = "`herominers`"

# ---------------- 连接 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()

# ---------------- 币种 -> 域名映射 ----------------
domain_map = {
    "CFX": "conflux.herominers.com",
    "IRON": "ironfish.herominers.com",
    "KLS": "karlsen.herominers.com",
    "RVN": "ravencoin.herominers.com",
    "ERG": "ergo.herominers.com",
    "XEL": "xelis.herominers.com",
}

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

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

def get_api_url(coin, wallet):
    domain = domain_map.get(coin)
    if coin == "CFX" and not wallet.startswith("cfx:"):
        wallet = f"cfx:{wallet}"
    return f"https://{domain}/api/stats_address?address={wallet}&recentBlocksAmount=20&longpoll=false"

def fetch_herominers_data(pool_name, coin, wallet, algorithm):
    url = get_api_url(coin, wallet)
    try:
        resp = requests.get(url, timeout=10)
        resp.raise_for_status()
        data = resp.json()

        workers = data.get("workers", [])
        if not workers:
            print(f"{coin} | {wallet} | {pool_name} ⚠ 当前没有任何在线矿机")
            return

        for worker in workers:
            name = worker.get("name", "unknown")
            hashrate = worker.get("hashrate", 0) / 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, (
                round_half_hour(),
                pool_name,
                wallet,
                name,
                hashrate,
                coin,
                algorithm
            ))
            conn.commit()
            print(f"{coin} | {pool_name} | {name}: {hashrate:.2f} MH/s 写入成功")

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


if __name__ == "__main__":
    for key in keys:
        parts = key.split(":")
        if len(parts) != 4:
            continue
        _, wallet, coin, algorithm = parts
        pool_name = parts[0]  # Redis key第一部分作为矿池名

        fetch_herominers_data(pool_name, coin, wallet, algorithm)

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