"""Test Eastmoney API response time for HK stocks"""
import urllib.request, json, time

codes = ['00700', '01888', '00981']
UA = 'Mozilla/5.0'

for code in codes:
    url = f"https://push2.eastmoney.com/api/qt/stock/get?secid=116.{code}&fields=f43,f170&fltt=2"
    start = time.time()
    try:
        req = urllib.request.Request(url, headers={"User-Agent": UA})
        with urllib.request.urlopen(req, timeout=30) as r:
            resp = json.loads(r.read().decode("utf-8"))
            elapsed = time.time() - start
            price = resp.get('data', {}).get('f43', '?')
            print(f"{code}: {elapsed:.1f}s, price={price}, rc={resp.get('rc')}")
    except Exception as e:
        elapsed = time.time() - start
        print(f"{code}: {elapsed:.1f}s, ERROR: {type(e).__name__}: {e}")

# Also test Tencent fallback
print("\nTencent fallback:")
url = "http://qt.gtimg.cn/q=hk00700,hk01888,hk00981"
start = time.time()
try:
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    with urllib.request.urlopen(req, timeout=10) as r:
        text = r.read().decode("gbk")
        elapsed = time.time() - start
        print(f"Tencent: {elapsed:.1f}s, {len(text)} bytes")
        # Parse first line
        line = text.strip().split('\n')[0]
        print(f"  sample: {line[:80]}...")
except Exception as e:
    elapsed = time.time() - start
    print(f"Tencent: {elapsed:.1f}s, ERROR: {e}")
