#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Bybit 주식/ETF 퍼프 신규 상장 감지 → 텔레그램
import json, os, re, urllib.request, urllib.parse, sys, datetime

BASE = os.path.expanduser("~/Claude/Projects/에이전트구축")
SNAP = os.path.join(BASE, "bybit_stocks.json")
NQLEV = os.path.join(BASE, "nq_levels.py")
DRY = "--dry" in sys.argv

# 뜨면 바로 알려야 할 것들 (ETF 대체재 우선)
PRIORITY = ("SOXX","SMH","XSD","PSI","FTXL","XLK","QQQ","IGV","VGT","IYW",
            "SKYY","AIQ","BOTZ","ARKK","EWY","EWT","EWJ")

def send(msg):
    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)
    d = urllib.parse.urlencode({"chat_id": cid, "text": msg}).encode()
    urllib.request.urlopen(f"https://api.telegram.org/bot{tok}/sendMessage", d, timeout=15)

u = "https://api.bybit.com/v5/market/instruments-info?category=linear&limit=1000"
req = urllib.request.Request(u, headers={"User-Agent": "Mozilla/5.0"})
d = json.load(urllib.request.urlopen(req, timeout=20))
cur = sorted({x["symbol"] for x in d["result"]["list"] if x.get("symbolType") == "stock"})

try:
    old = json.load(open(SNAP, encoding="utf-8"))
    prev = sorted({x["symbol"] if isinstance(x, dict) else x
                   for x in (old.get("list") if isinstance(old, dict) else old)})
except Exception:
    prev = []

new = [s for s in cur if s not in prev]
gone = [s for s in prev if s not in cur]

json.dump({"date": str(datetime.date.today()), "count": len(cur), "list": cur},
          open(SNAP, "w", encoding="utf-8"), ensure_ascii=False, indent=1)

if not prev:
    print(f"기준 스냅샷 생성: {len(cur)}개"); sys.exit()

lines = []
if new:
    hot = [s for s in new if s.replace("USDT","").replace("STOCK","") in PRIORITY]
    if hot: lines.append("★ 관심 ETF 상장: " + ", ".join(hot))
    lines.append("신규 " + str(len(new)) + "건: " + ", ".join(new))
if gone:
    lines.append("상장폐지 " + str(len(gone)) + "건: " + ", ".join(gone))

if lines:
    msg = f"[Bybit 종목 변동 {datetime.date.today()}] 총 {len(cur)}개\n" + "\n".join(lines)
    print(msg)
    if not DRY: send(msg)
else:
    print(f"변동 없음 (총 {len(cur)}개)")
