#!/usr/bin/env python3
"""Analyse détaillée des performances du Market Spy"""
import json, os
import numpy as np

f = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'espion_history.json')
if not os.path.exists(f):
    print("Pas d'historique spy")
    exit()

with open(f, 'r') as fh:
    h = json.load(fh)

print(f"Total trades: {len(h)}")
wins = [t for t in h if t['pnl_pct'] > 0]
losses = [t for t in h if t['pnl_pct'] <= 0]
print(f"Wins: {len(wins)}, Losses: {len(losses)}")
total_pnl = sum(t.get('pnl_usdt', 0) for t in h)
print(f"Total PnL: {total_pnl:+.4f} USDT")
print()

# Exit reasons analysis
reasons = {}
for t in h:
    r = t.get('exit_reason', 'unknown').split(' ')[0]
    if r not in reasons:
        reasons[r] = {'count': 0, 'pnl': 0, 'pnl_list': []}
    reasons[r]['count'] += 1
    reasons[r]['pnl'] += t.get('pnl_usdt', 0)
    reasons[r]['pnl_list'].append(t['pnl_pct'])

print("EXIT REASONS:")
for r, d in sorted(reasons.items(), key=lambda x: -x[1]['count']):
    avg_pnl = sum(d['pnl_list']) / len(d['pnl_list'])
    print(f"  {r}: {d['count']}x | PnL: {d['pnl']:+.4f} USDT | Avg: {avg_pnl:+.2f}%")
print()

# Hold time analysis
print("HOLD TIME ANALYSIS:")
short = [t for t in h if t.get('hold_minutes', 0) < 5]
med = [t for t in h if 5 <= t.get('hold_minutes', 0) < 15]
long_t = [t for t in h if t.get('hold_minutes', 0) >= 15]
for label, grp in [('<5min', short), ('5-15min', med), ('>15min', long_t)]:
    if grp:
        avg = sum(t['pnl_pct'] for t in grp) / len(grp)
        wr = sum(1 for t in grp if t['pnl_pct'] > 0) / len(grp) * 100
        total = sum(t.get('pnl_usdt', 0) for t in grp)
        print(f"  {label}: {len(grp)} trades | Avg: {avg:+.2f}% | WR: {wr:.0f}% | PnL: {total:+.4f} USDT")
print()

# Max PnL vs actual PnL (gains left on table)
print("GAINS LEFT ON TABLE (last 30):")
total_left = 0
for t in h[-30:]:
    if t.get('max_pnl', 0) > 0:
        left = t['max_pnl'] - t['pnl_pct']
        total_left += left
        if left > 0.5:
            print(f"  {t['symbol']}: max={t['max_pnl']:+.2f}% sold={t['pnl_pct']:+.2f}% "
                  f"left={left:+.2f}% ({t['exit_reason']}) hold={t.get('hold_minutes', 0):.1f}min")
print(f"  --> Total gains left: {total_left:+.2f}%")
print()

# Surge type analysis
print("SURGE TYPE PERFORMANCE:")
stypes = {}
for t in h:
    st = t.get('surge_type', 'unknown')
    if st not in stypes:
        stypes[st] = {'count': 0, 'pnl': 0, 'wins': 0}
    stypes[st]['count'] += 1
    stypes[st]['pnl'] += t.get('pnl_usdt', 0)
    if t['pnl_pct'] > 0:
        stypes[st]['wins'] += 1
for st, d in sorted(stypes.items(), key=lambda x: -x[1]['count']):
    wr = d['wins'] / d['count'] * 100
    print(f"  {st}: {d['count']}x | WR: {wr:.0f}% | PnL: {d['pnl']:+.4f} USDT")
print()

# Strength analysis
print("SURGE STRENGTH ANALYSIS:")
weak = [t for t in h if t.get('surge_strength', 0) < 1.5]
med_s = [t for t in h if 1.5 <= t.get('surge_strength', 0) < 3.0]
strong = [t for t in h if t.get('surge_strength', 0) >= 3.0]
for label, grp in [('<1.5%', weak), ('1.5-3%', med_s), ('>3%', strong)]:
    if grp:
        avg = sum(t['pnl_pct'] for t in grp) / len(grp)
        wr = sum(1 for t in grp if t['pnl_pct'] > 0) / len(grp) * 100
        total = sum(t.get('pnl_usdt', 0) for t in grp)
        print(f"  {label}: {len(grp)} trades | Avg: {avg:+.2f}% | WR: {wr:.0f}% | PnL: {total:+.4f} USDT")
print()

# Detailed last 15 trades
print("LAST 15 TRADES:")
for t in h[-15:]:
    emoji = "✅" if t['pnl_pct'] > 0 else "❌"
    print(f"  {emoji} {t['symbol']:12s} | PnL: {t['pnl_pct']:+.2f}% ({t.get('pnl_usdt', 0):+.4f} USDT) | "
          f"Max: {t.get('max_pnl', 0):+.2f}% | Hold: {t.get('hold_minutes', 0):.1f}min | "
          f"Surge: {t.get('surge_type', '')} {t.get('surge_strength', 0):.1f}% | "
          f"Exit: {t.get('exit_reason', '')}")
