#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Bybit 공지 감시: 상장폐지/정산/계약변경 → 텔레그램 즉시
import json, os, re, urllib.request, urllib.parse, sys, datetime

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

# 내 포지션 종목 — 여기 걸리면 최우선
MINE = ("DRAM","MU","NBIS","SOXL","AAOI","SNDK","BTC","ETH","SOL","KORU","EWY")
HOT = re.compile(r"(delist|delisting|settle|settlement|상장.?폐지|정산|종료|"
                 r"contract.*(change|adjust)|leverage.*(adjust|change)|"
                 r"risk limit|auto.?deleverag|ADL|suspend)", re.I)

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,
                                "disable_web_page_preview": "true"}).encode()
    urllib.request.urlopen(f"https://api.telegram.org/bot{tok}/sendMessage", d, timeout=15)

try: seen = set(json.load(open(SEEN)))
except Exception: seen = set()

out = []
for t in ("delistings", "latest_activities", "new_crypto", "product_updates"):
    try:
        u = f"https://api.bybit.com/v5/announcements/index?locale=en-US&type={t}&limit=30"
        r = urllib.request.Request(u, headers={"User-Agent": "Mozilla/5.0"})
        d = json.load(urllib.request.urlopen(r, timeout=20))
        for a in d.get("result", {}).get("list", []):
            url = a.get("url", ""); title = a.get("title", "")
            if not url or url in seen: continue
            if not HOT.search(title) and t != "delistings": continue
            mine = [m for m in MINE if re.search(r"\b" + m + r"\b", title, re.I)]
            tag = "★내포지션 " + "/".join(mine) if mine else ""
            out.append(f"{tag}\n{title}\n{url}")
            seen.add(url)
    except Exception as e:
        print(f"{t} 조회실패: {e}")

if out:
    msg = "[Bybit 공지]\n\n" + "\n\n".join(out[:8])
    print(msg)
    if not DRY: send(msg)
else:
    print("신규 공지 없음")
json.dump(list(seen)[-500:], open(SEEN, "w"))
