#!/usr/bin/env python3
import subprocess, json, os, re
from datetime import datetime, timezone, timedelta

BASE = os.path.expanduser("~/Claude/Projects/에이전트구축")
AS_FILE = os.path.join(BASE, "x_scrape_accounts.applescript")

# Bybit 종목 로드 (대조용)
with open(os.path.join(BASE, "bybit_stocks.json")) as f:
    bybit = {s["ticker"] for s in json.load(f)["stocks"]}

r = subprocess.run(['osascript', AS_FILE, '1ChartMaster'], capture_output=True, text=True, timeout=90)
raw = r.stdout.strip()

cutoff = datetime.now(timezone.utc) - timedelta(days=7)
tweets = []
for item in raw.split('###'):
    parts = item.split('@@@')
    if len(parts) != 3: continue
    pub, text, url = parts[0].strip(), parts[1].strip(), parts[2].strip()
    try:
        pubdt = datetime.fromisoformat(pub.replace('Z','+00:00'))
        if pubdt < cutoff: continue
    except: pass
    # $TICKER 패턴 추출
    tickers = re.findall(r'\$([A-Z]{1,5})', text)
    bybit_hits = [t for t in tickers if t in bybit]
    tweets.append({"pub": pub, "text": text[:200], "tickers": tickers, "bybit": bybit_hits, "url": url})

# 결과 파일로 저장
with open(os.path.join(BASE, "1chartmaster_week.json"), "w") as f:
    json.dump(tweets, f, ensure_ascii=False, indent=1)

print(f"수집된 트윗: {len(tweets)}개")
print("=== Bybit 거래가능 종목이 언급된 트윗 ===")
for t in tweets:
    if t["bybit"]:
        print(f"{t['pub'][:16]} | {','.join(t['bybit'])} | {t['text'][:80]}")
