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

# ---------------- Redis 配置 ----------------
r = redis.Redis(host='127.0.0.1', port=6379, db=7, decode_responses=True)

# ---------------- MySQL 配置 ----------------
conn = pymysql.connect(
    host='127.0.0.1',
    user='root',
    password='123456',
    database='pool',
    port=25600,
    charset='utf8mb4'
)
cursor = conn.cursor()

# ---------------- API 配置 ----------------
API_URLS = {
    "NEXA": "https://nexa.2miners.com/api/accounts/{wallet}",
    "XNA": "https://xna.2miners.com/api/accounts/{wallet}",
    "CLORE": "https://clore.2miners.com/api/accounts/{wallet}",
    "RVN": "https://rvn.2miners.com/api/accounts/{wallet}",
    "ERG": "https://erg.2miners.com/api/accounts/{wallet}"
}

# ---------------- 工具函数 ----------------
def to_mhs(value):
    """算力转换为 MH/s"""
    return float(value) / 1_000_000 if value else 0.0

def get_half_hour_time(now):
    """取最近半点整时间"""
    minute = 0 if now.minute < 30 else 30
    return now.replace(minute=minute, second=0, microsecond=0)

# ---------------- 主逻辑（单次执行） ----------------
def run_once():
    keys = r.keys("*")
    half_time = get_half_hour_time(datetime.now())

    for key in keys:
        try:
            parts = key.split(":")
            if len(parts) != 4:
                continue

            pool_name, wallet, coin, algo = parts
            if pool_name.lower() != "2miners":
                continue  # 只处理2miners

            coin_upper = coin.upper()
            if coin_upper not in API_URLS:
                print(f"[跳过] 不支持币种 {coin_upper}")
                continue

            # NEXA 需要补全前缀
            wallet_api = f"nexa:{wallet}" if coin_upper=="NEXA" and not wallet.startswith("nexa:") else wallet

            url = API_URLS[coin_upper].format(wallet=wallet_api)
            resp = requests.get(url, timeout=10)
            resp.raise_for_status()
            data = resp.json()

            workers = data.get("workers", {})
            if not workers:
                print(f"[无矿机] {coin_upper} {wallet}")
                continue

            for miner, info in workers.items():
                hashrate = to_mhs(info.get("hr"))
                print(f"写入 → {coin_upper} | {miner} | {hashrate:.2f} MH/s")

                sql = """
                    INSERT INTO `2miners`
                    (datetime,pool_name,wallet,miner,hashrate,coin,algorithm)
                    VALUES (%s,%s,%s,%s,%s,%s,%s)
                """
                cursor.execute(sql,(half_time,pool_name,wallet,miner,hashrate,coin_upper,algo))
                conn.commit()

        except Exception as e:
            print(f"[错误] {key} ->", e)

# ---------------- 执行一次后退出 ----------------
if __name__ == "__main__":
    run_once()
    cursor.close()
    conn.close()
    print("✔ 本次采集结束")