import redis
import requests
from bs4 import BeautifulSoup
import pymysql
from datetime import datetime
import time

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

# URL 模板
BASE_URL = "https://pool.kryptex.com/zh-cn/{coin}/miner/stats/{wallet}"
HEADERS = {"User-Agent": "Mozilla/5.0"}


def to_mhs(value: str):
    """自动将各种单位算力字符串转换成 MH/s 纯数字值"""
    value = value.strip().lower()
    if "gh/s" in value: return float(value.replace("gh/s", "")) * 1000
    if "mh/s" in value: return float(value.replace("mh/s", ""))
    if "kh/s" in value: return float(value.replace("kh/s", "")) / 1000
    if "h/s" in value:  return float(value.replace("h/s", "")) / 1_000_000
    return 0.0


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


def query_and_insert():
    keys = r.keys("*")
    half_hour_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 != "pool.kryptex":
                continue

            coin_lower = coin.lower()
            coin_for_url = "xtm-c29" if coin_lower == "xtm" else coin_lower
            url = BASE_URL.format(coin=coin_for_url, wallet=wallet.lower())

            resp = requests.get(url, headers=HEADERS, timeout=10)
            resp.raise_for_status()

            soup = BeautifulSoup(resp.text, "html.parser")
            tbody = soup.find("tbody")
            if not tbody:
                print(f"❗无矿工数据 {wallet} {coin}")
                continue

            for row in tbody.find_all("tr"):
                try:
                    worker = row.find("th").find("a").text.strip()
                    mhs = to_mhs(row.find_all("td")[5].text.strip())

                    print(f"[OK] {coin}:{wallet} {worker} -> {mhs:.2f} MH/s")

                    sql = """
                    INSERT INTO `pool.kryptex`
                    (datetime, pool_name, wallet, miner, hashrate, coin, algorithm)
                    VALUES (%s,%s,%s,%s,%s,%s,%s)
                    """
                    cursor.execute(sql, (half_hour_time, pool_name, wallet, worker, mhs, coin.upper(), algo))
                    conn.commit()

                except Exception as e:
                    print("解析矿工失败 =>", e)

        except Exception as e:
            print("请求失败 =>", e)


if __name__ == "__main__":
    query_and_insert()
    cursor.close()
    conn.close()
    print("✔ 采集完成，程序已退出")