#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 유럽장 흐름 vs 미국 프리마켓 괴리 탐지 (미국 개장 45분 전 실행)
import re, os, sys, datetime, urllib.request, urllib.parse
import yfinance as yf

BASE = os.path.expanduser("~/Claude/Projects/에이전트구축")
NQLEV = os.path.join(BASE, "nq_levels.py")
DRY = "--dry" in sys.argv
WATCH = ["NBIS","CRWV","IREN","MU","SNDK","AAOI","LITE","META","NVDA","SOXL","TER","ALAB"]

def send(msg):
    try:
        s = open(NQLEV, encoding="utf-8").read()
        tok = re.search(r'BOT_TOKEN\s*=\s*["\']([^"\']+)', s).group(1)
        cid = re.search(r'CHAT_ID\s*=\s*["\']?([^"\'\s]+)', s).group(1)
    except Exception:
        print("[!] 토큰 없음"); return
    d = urllib.parse.urlencode({"chat_id": cid, "text": msg}).encode()
    urllib.request.urlopen(f"https://api.telegram.org/bot{tok}/sendMessage", d, timeout=15)

lines = []
for tk in WATCH:
    try:
        t = yf.Ticker(tk)
        prev = t.fast_info.get("previous_close")
        pre = t.fast_info.get("last_price")
        if not prev or not pre: continue
        ch = (pre / prev - 1) * 100
        if abs(ch) >= 1.5:
            lines.append(f"{tk} {ch:+.2f}% (전일종가 {prev:.2f} → 프리 {pre:.2f})")
    except Exception:
        continue

msg = f"[개장전 갭 {datetime.date.today()}]\n" + ("\n".join(lines) if lines else "1.5% 이상 갭 없음")
msg += "\n\n유럽장 강세를 프리마켓에서 반납 중이면 미국이 반대로 읽는 중."
print(msg)
if not DRY: send(msg)
