#!/opt/homebrew/bin/python3
# Valley AI 데일리 브리핑 vs 우리 수집 대조 → 미포착 갭 + 룰개선 제안 (방콕 09:30 실행)
import json, re, subprocess
from datetime import datetime, timezone, timedelta

BASE = "/Users/sean/Claude/Projects/에이전트구축/"
AS = BASE + "x_scrape_accounts.applescript"
BKK = timezone(timedelta(hours=7))
today_bkk = datetime.now(BKK).date()

def tg(msg):
    # 기존 alert.py의 텔레그램 함수 재사용 경로가 있으면 그걸 쓰고, 없으면 print
    try:
        import telegram_send  # 있으면
        telegram_send.send(messages=[msg])
    except Exception:
        print(msg)

# Valley AI 긁기
try:
    r = subprocess.run(['osascript', AS, 'ValleyAI_X'], capture_output=True, text=True, timeout=90)
    raw = r.stdout
except Exception as e:
    tg(f"[갭점검] Valley 스크래핑 실패: {e}"); raise SystemExit

# 최신 브리핑 블록 추출 + 오늘 것인지 확인
blocks = [b for b in raw.split('###') if ('정치' in b and '매크로' in b) or '오늘의 핵심 뉴스' in b]
if not blocks:
    tg(f"[갭점검 {today_bkk}] Valley AI 오늘 브리핑 아직 안 뜸 — 나중에 재확인 필요")
    raise SystemExit
brief = blocks[0]
parts = brief.split('@@@')
pub_ok = True
if len(parts) >= 1 and parts[0].strip():
    try:
        dt = datetime.fromisoformat(parts[0].strip().replace('Z','+00:00'))
        if dt.astimezone(BKK).date() != today_bkk:
            tg(f"[갭점검 {today_bkk}] 최신 Valley 브리핑이 오늘 것 아님({dt.astimezone(BKK).date()}) — skip")
            raise SystemExit
    except SystemExit: raise
    except: pass

# 티커·이벤트 추출
tickers = set(re.findall(r'\$([A-Z]{2,5})', brief))
KEYEVENTS = ['관세','tariff','301','cpi','pce','fomc','연준','해맥','제퍼슨','미시간','소비자심리',
 '기대인플','주택착공','산업생산','수입물가','호르무즈','흑해','드론','ipo','상장','수주','계약',
 'kimi','qwen','deepseek','glm','xai','grok','데이터브릭스','스페이스x','폭스콘']
found_ev = [k for k in KEYEVENTS if k.lower() in brief.lower()]

def load_text(fn):
    t=""
    try:
        for line in open(BASE+fn, encoding='utf-8'):
            try: t += json.loads(line).get('text','')+" "
            except: pass
    except: pass
    return t.lower()
ours = load_text('media_feed.jsonl') + load_text('x_feed.jsonl')

missed_t = [t for t in tickers if t.lower() not in ours]
missed_e = [e for e in found_ev if e.lower() not in ours]

log = BASE + "gap_valley_log.jsonl"
with open(log,'a',encoding='utf-8') as f:
    f.write(json.dumps({"date":str(today_bkk),"missed_tickers":missed_t,"missed_events":missed_e},ensure_ascii=False)+"\n")

from collections import Counter
cnt=Counter()
for line in open(log,encoding='utf-8'):
    try:
        for e in json.loads(line).get('missed_events',[]): cnt[e]+=1
    except: pass
repeat={k:v for k,v in cnt.items() if v>=2}

msg=[f"[갭점검 {today_bkk}]"]
msg.append(f"미포착 종목: {', '.join(missed_t) if missed_t else '없음'}")
msg.append(f"미포착 이벤트: {', '.join(missed_e) if missed_e else '없음'}")
if repeat:
    msg.append(f"\n[!] 2회+ 반복 미포착: {repeat}")
    msg.append("→ Claude에게 '갭점검' 물으면 룰 개선안 제안")
tg("\n".join(msg))
