"""Analyse du Market Spy depuis 7h le 8 mars 2026."""
import json
import datetime

# --- Historique des trades spy terminés ---
with open('espion_history.json', encoding='utf-8') as f:
    trades = json.load(f)

cutoff = datetime.datetime(2026, 3, 8, 7, 0, 0)

today = []
for t in trades:
    for key in ('exit_time', 'entry_time', 'timestamp'):
        ts = t.get(key)
        if ts:
            try:
                dt = datetime.datetime.fromisoformat(str(ts).replace('Z', ''))
                if dt >= cutoff:
                    today.append((dt, t))
            except Exception:
                pass
            break

today.sort(key=lambda x: x[0])
print(f"=== TRADES SPY DEPUIS 7H ({len(today)}) ===")
for dt, t in today:
    sym = t.get('symbol', '?')
    pnl = t.get('pnl_pct', t.get('pnl', '?'))
    entry = t.get('entry_price', '?')
    sell = t.get('sell_price', '?')
    reason = t.get('exit_reason', t.get('sell_reason', '?'))
    surge = t.get('surge_type', '?')
    hold = t.get('hold_minutes', '?')
    pnl_str = f"{float(pnl):+.2f}%" if pnl not in ('?', None) else '?'
    hour = dt.strftime("%H:%M")
    print(f"  {hour}  {sym:<14s}  pnl={pnl_str:<9s}  entry={entry}  sell={sell}  surge={surge}  hold={hold}min  raison={reason}")

# --- Opportunités détectées ---
print()
with open('espion_opportunities.json', encoding='utf-8') as f:
    opps = json.load(f)

today_opps = []
for o in opps:
    ts = o.get('timestamp')
    if ts:
        try:
            dt = datetime.datetime.fromisoformat(str(ts).replace('Z', ''))
            if dt >= cutoff:
                today_opps.append((dt, o))
        except Exception:
            pass

today_opps.sort(key=lambda x: x[0])
print(f"=== OPPORTUNITES DETECTEES DEPUIS 7H ({len(today_opps)}) ===")
skipped = {}
bought = 0
for dt, o in today_opps:
    sym = o.get('symbol', '?')
    score = o.get('score', '?')
    reason = o.get('reason', '')
    executed = o.get('executed', False)
    pattern = o.get('pattern', '?')
    ind = o.get('indicators', {})
    surge = ind.get('surge_strength', ind.get('change_1scan', '?'))
    vol = ind.get('volume_spike', ind.get('vol_ratio', '?'))
    hour = dt.strftime("%H:%M")
    if executed:
        bought += 1
        print(f"  {hour}  ✅ ACHETE  {sym:<14s}  score={score}  surge={surge}  vol={vol}x  pattern={pattern}")
    else:
        skipped[reason] = skipped.get(reason, 0) + 1

print(f"\n  Achetés: {bought}")
print(f"  Ignorés par raison:")
for r, c in sorted(skipped.items(), key=lambda x: -x[1]):
    print(f"    {r}: {c}x")

# --- Spy status ---
print()
with open('spy_status.json', encoding='utf-8') as f:
    status = json.load(f)
print("=== SPY STATUS ===")
for k, v in status.items():
    print(f"  {k}: {v}")

# --- Opportunités récentes non achetées avec score élevé ---
print()
print("=== OPPORTUNITES MANQUEES (score>=70, non acheté) depuis 7h ===")
missed = [(dt, o) for dt, o in today_opps if not o.get('executed') and o.get('score', 0) >= 70]
missed.sort(key=lambda x: -x[1].get('score', 0))
for dt, o in missed[:30]:
    sym = o.get('symbol', '?')
    score = o.get('score', '?')
    reason = o.get('reason', '?')
    pattern = o.get('pattern', '?')
    ind = o.get('indicators', {})
    surge = ind.get('surge_strength', ind.get('change_1scan', '?'))
    vol = ind.get('volume_spike', ind.get('vol_ratio', '?'))
    hour = dt.strftime("%H:%M")
    print(f"  {hour}  {sym:<14s}  score={score:<6}  raison={reason:<30s}  surge={surge}  vol={vol}x  pattern={pattern}")
