#!/usr/bin/env python3
from __future__ import annotations

import json
import subprocess
from pathlib import Path

REPO = Path('/home/agent/projects/CryptoTradingBot/Crypto_Agent')
RADAR = REPO / 'runtime/research/coin_opportunity_radar_latest.json'
STATE = REPO / 'runtime/research/coin_opportunity_radar_alert_state.json'

subprocess.run([
    str(REPO / '.venv/bin/python'), '-m', 'src.tools.coin_opportunity_radar',
    '--output', str(RADAR),
], cwd=str(REPO), check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

try:
    data = json.loads(RADAR.read_text(encoding='utf-8'))
except Exception:
    raise SystemExit(0)
try:
    state = json.loads(STATE.read_text(encoding='utf-8'))
except Exception:
    state = {'alerted_keys': []}
alerted = set(state.get('alerted_keys') or [])
new_lines = []
for sym in data.get('new_hyperliquid_symbols') or []:
    key = f'new_hl:{sym}'
    if key not in alerted:
        new_lines.append(f'🆕 Neuer Hyperliquid-Markt: {sym}')
        alerted.add(key)
for row in data.get('opportunities', [])[:20]:
    sym = row.get('symbol')
    reasons = row.get('reasons') or []
    score = row.get('opportunity_score')
    # Alert only actionable research candidates: real pump/dump or trending with high score.
    interesting = any(r in reasons for r in ('strong_1h_pump','strong_24h_pump','sharp_1h_selloff','sharp_24h_selloff')) or ('coingecko_trending' in reasons and str(score) >= '85')
    key = f"opp:{sym}:{','.join(reasons[:4])}:{score}"
    if sym and interesting and key not in alerted:
        new_lines.append(f"👀 {sym}: score={score}, Gründe={', '.join(reasons[:4])}")
        alerted.add(key)
if new_lines:
    STATE.parent.mkdir(parents=True, exist_ok=True)
    STATE.write_text(json.dumps({'alerted_keys': sorted(alerted)[-500:]}, indent=2), encoding='utf-8')
    print('Coin Opportunity Radar\n' + '\n'.join(new_lines[:12]) + '\nResearch-only: keine Live-Orders.')
