#!/usr/bin/env python3
"""Verify ticker names (skill v2.0 naming discipline) + compute position P&L."""
import re, ssl, urllib.request, json, html as H
ctx = ssl.create_default_context(); ctx.check_hostname = False; ctx.verify_mode = ssl.CERT_NONE
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0 Safari/537.36"}

print("=== ticker identity verification ===")
for code in ("00412A.TW", "6669.TW"):
    u = f"https://query1.finance.yahoo.com/v8/finance/chart/{code}?range=5d&interval=1d"
    try:
        x = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=25, context=ctx).read().decode()
        m = re.search(r'"longName"\s*:\s*"([^"]+)"', x) or re.search(r'"shortName"\s*:\s*"([^"]+)"', x)
        print(f"  {code}: {m.group(1) if m else 'N/A (chart endpoint has no longName)'}")
    except Exception as e:
        print(f"  {code}: FAIL {type(e).__name__}: {e}")

# yfinance longName
try:
    import yfinance as yf
    for code in ("00412A.TW", "6669.TW"):
        try:
            i = yf.Ticker(code).info
            print(f"  yf {code}: longName={i.get('longName')} | shortName={i.get('shortName')}")
        except Exception as e:
            print(f"  yf {code}: FAIL {type(e).__name__}: {e}")
except Exception as e:
    print("  no yfinance:", e)

print("\n=== position P&L (skill v2 baseline) ===")
d = json.load(open("/root/.hermes/cron/output/_clean_20261026.json"))
p9 = d["6669"]["close"]; p412 = d["00412A"]["close"]
n9, c9 = 258, 1737.0
n412, c412 = 15000, 9.43
v9, v412 = n9*p9, n412*p412
cost9, cost412 = n9*c9, n412*c412
print(f"  6669: {n9} x {p9:.2f} = {v9:,.0f} | cost {cost9:,.0f} | P&L {v9-cost9:+,.0f} ({(v9/cost9-1)*100:+.2f}%)")
print(f"  00412A: {n412:,} x {p412:.2f} = {v412:,.0f} | cost {cost412:,.0f} | P&L {v412-cost412:+,.0f} ({(v412/cost412-1)*100:+.2f}%)")
tot, tc = v9+v412, cost9+cost412
print(f"  TOTAL: {tot:,.0f} | cost {tc:,.0f} | P&L {tot-tc:+,.0f} ({(tot/tc-1)*100:+.2f}%)")

print("\n=== 6669 trigger evaluation (skill v2) ===")
n = d["6669"]
gap = lambda now, thr: (now-thr)/thr*100
print(f"  RSI {n['rsi']} vs <=28 -> {gap(n['rsi'],28):+.1f}%  (add cond 1 {'MET' if n['rsi']<=28 else 'not met'})")
print(f"  vol_ratio {n['vol_ratio']:.2f} vs <=0.70 -> {gap(n['vol_ratio'],0.70):+.1f}%  (add cond 2 {'MET' if n['vol_ratio']<=0.70 else 'not met'})")
print(f"  K {n['k']} D {n['d']} golden cross? {'YES' if n['prev_k']<=n['prev_d'] and n['k']>n['d'] else 'NO'} (add cond 3)")
print(f"  TRIM 2030: close {p9:.0f} -> {gap(p9,2030):+.1f}%")
print(f"  TRIM 2128 (MA20): close {p9:.0f}, MA20 {n['ma20']:.1f} -> {gap(p9,2128):+.1f}%; hist {n['hist']:.2f} negative={n['hist']<0}")
print(f"  TRIM 1810 (20d low {n['low20']:.0f}): close {p9:.0f} -> {gap(p9,1810):+.1f}%")
print(f"  TRIM 1720: close {p9:.0f} -> {gap(p9,1720):+.1f}%")
print(f"  FULL EXIT #1: consecutive closes below MA60 = {n['consec_below_ma60']} (threshold 3) -> {'TRIGGERED' if n['consec_below_ma60']>=3 else 'no'}")
print(f"  FULL EXIT #2: CRWV CDS>1500 AND HY-IG>500 — CDS ~1194bps (<1500) -> condition depends on HY-IG (N/A)")
print(f"  FULL EXIT #3: hyperscaler capex guidance cut >=10% — none reported")

print("\n=== 00412A trigger evaluation (skill v2) ===")
a = d["00412A"]
print(f"  close {a['close']:.2f} vs stop 8.00 -> {gap(a['close'],8.0):+.1f}%  (stop {'TRIGGERED' if a['close']<8.0 else 'not triggered'})")
for tp in (12.0, 14.0, 16.0):
    print(f"  take-profit {tp}: {gap(a['close'],tp):+.1f}%  ({'reached' if a['close']>=tp else 'not reached'})")
print(f"  hold zone 8.50-12.0 -> {'IN HOLD ZONE' if 8.5<=a['close']<=12.0 else 'OUTSIDE'}")
print(f"  bars since first listing: {a['bars']} (first {a['first_date']} close {a['first_close']})")
print(f"  vs cost 9.43: {gap(a['close'],9.43):+.1f}%")
