"""Mostra lo stato del paper trader."""
from __future__ import annotations
import sys
sys.path.insert(0, ".")

import json
from pathlib import Path
from src.live.cerbero_client import CerberoClient

LOG_DIR = Path("data/paper_trades")

print("=" * 50)
print("  PAPER TRADER STATUS")
print("=" * 50)

# Status file
status_path = LOG_DIR / "status.json"
if status_path.exists():
    with open(status_path) as f:
        status = json.load(f)
    print(f"\n  In posizione: {status['in_position']}")
    if status["in_position"]:
        print(f"  Direzione:    {status['direction']}")
        print(f"  Entry price:  {status['entry_price']}")
        print(f"  Entry time:   {status['entry_time']}")
        print(f"  Barre tenute: {status['bars_held']}")
    print(f"  Ultimo update: {status['last_update']}")
else:
    print("\n  Nessun file di stato trovato.")

# Account
print("\n--- ACCOUNT DERIBIT TESTNET ---")
c = CerberoClient()
try:
    acc = c.get_account_summary("USDC")
    print(f"  Equity:  ${acc['equity']:,.2f}")
    print(f"  Balance: ${acc['balance']:,.2f}")
    print(f"  PnL:     ${acc['total_pnl']:,.2f}")
except Exception as e:
    print(f"  Errore: {e}")

# Posizioni
try:
    pos = c.get_positions("USDC")
    print(f"\n  Posizioni aperte: {len(pos)}")
    for p in pos:
        print(f"    {p.get('instrument','?')}: {p.get('size',0)} {p.get('direction','?')} @ ${p.get('avg_price',0)}")
except Exception as e:
    print(f"  Errore: {e}")

# Ultimi log
print("\n--- ULTIMI LOG ---")
log_files = sorted(LOG_DIR.glob("trades_*.jsonl"))
if log_files:
    with open(log_files[-1]) as f:
        lines = f.readlines()
    for line in lines[-10:]:
        entry = json.loads(line)
        print(f"  [{entry['timestamp'][:19]}] {entry['event']}")
else:
    print("  Nessun log trovato.")

# Statistiche trade
all_trades = []
for lf in log_files:
    with open(lf) as f:
        for line in f:
            entry = json.loads(line)
            if entry["event"] == "CLOSED":
                all_trades.append(entry)

if all_trades:
    wins = sum(1 for t in all_trades if t.get("pnl_pct", 0) > 0)
    total = len(all_trades)
    total_pnl = sum(t.get("pnl_pct", 0) for t in all_trades)
    print(f"\n--- STATISTICHE ---")
    print(f"  Trade chiusi: {total}")
    print(f"  Win rate:     {wins/total*100:.0f}%")
    print(f"  PnL totale:   {total_pnl:.2f}%")
