#!/usr/bin/env python3
"""
Enrichit les positions en utilisant les prix historiques Binance
Estimation des données manquantes basée sur timestamps et margin
"""

import json
import os
import requests
from datetime import datetime
from typing import Optional

POSITIONS_FILE = 'positions.json'


def get_btc_price_at_timestamp(timestamp_str: str) -> Optional[float]:
    """Récupère le prix BTC depuis Binance à un timestamp ISO"""
    try:
        dt = datetime.fromisoformat(timestamp_str.replace('Z', '+00:00'))
        unix_ts = int(dt.timestamp() * 1000)

        url = "https://api.binance.com/api/v3/klines"
        params = {
            'symbol': 'BTCUSDT',
            'interval': '5m',
            'startTime': unix_ts - 300000,  # -5min
            'endTime': unix_ts + 300000,    # +5min
            'limit': 1
        }

        response = requests.get(url, params=params, timeout=5)
        response.raise_for_status()
        data = response.json()

        if data:
            return float(data[0][1])  # Open price
        return None
    except Exception as e:
        print(f"   ⚠️  Erreur prix: {e}")
        return None


def enrich_position(position: dict) -> bool:
    """Enrichit une position avec des estimations raisonnables"""

    symbol = position.get('symbol', 'UNKNOWN')
    print(f"\n   🔍 {symbol} - {position.get('status', 'UNKNOWN')}")

    # 1. Entry price depuis timestamp d'ouverture (si manquant)
    entry_price = position.get('entry_price', 0)
    if entry_price == 0:
        opened_at = position.get('opened_at')
        if not opened_at:
            print(f"      ❌ Pas de timestamp d'ouverture")
            return False

        entry_price = get_btc_price_at_timestamp(opened_at)
        if not entry_price:
            print(f"      ❌ Impossible de récupérer entry_price")
            return False

        position['entry_price'] = entry_price

        # 2. Estimer margin et leverage (si manquants)
        margin = position.get('margin', 25.0)
        leverage = position.get('leverage', 150)

        position['margin'] = margin
        position['leverage'] = leverage

        # 3. Calculer qty
        qty = (margin * leverage) / entry_price
        position['qty'] = qty

        print(f"      ✅ Entry: ${entry_price:,.2f} | Margin: ${margin:.0f} | Lev: {leverage}x | Qty: {qty:.4f}")

    # 4. Exit price pour positions fermées (toujours calculer si manquant)
    if position.get('status') in ['CLOSED', 'LIQUIDATED']:
        # Skip si exit_price déjà calculé
        exit_price_val = position.get('exit_price') or 0
        pnl_val = position.get('pnl')
        if exit_price_val > 0 and pnl_val is not None:
            return False

        closed_at = position.get('closed_at')
        if closed_at:
            exit_price = get_btc_price_at_timestamp(closed_at)
            if exit_price:
                position['exit_price'] = exit_price

                # 5. Calculer PnL
                is_long = position.get('is_long', True)
                margin = position.get('margin', 25.0)
                leverage = position.get('leverage', 150)

                if is_long:
                    pnl_pct = (exit_price - entry_price) / entry_price
                else:
                    pnl_pct = (entry_price - exit_price) / entry_price

                pnl_usd = pnl_pct * margin * leverage

                position['pnl'] = round(pnl_usd, 2)
                position['pnl_pct'] = round(pnl_pct * 100, 2)

                print(f"      💰 Exit: ${exit_price:,.2f} | PnL: ${pnl_usd:+.2f} ({pnl_pct*100:+.2f}%)")
                return True

    return False


def main():
    """Enrichit toutes les positions"""

    print("=" * 80)
    print("📈 ENRICHISSEMENT VIA PRIX HISTORIQUES BINANCE")
    print("=" * 80)
    print()

    if not os.path.exists(POSITIONS_FILE):
        print(f"❌ Fichier {POSITIONS_FILE} non trouvé")
        return

    with open(POSITIONS_FILE, 'r') as f:
        data = json.load(f)

    positions = data.get('positions', {})
    print(f"📂 {len(positions)} positions trouvées\n")

    enriched_count = 0
    for trade_hash, position in positions.items():
        if enrich_position(position):
            enriched_count += 1

    # Sauvegarder
    if enriched_count > 0:
        data['last_updated'] = datetime.now().isoformat()

        with open(POSITIONS_FILE, 'w') as f:
            json.dump(data, f, indent=2)

        print()
        print("=" * 80)
        print(f"✅ {enriched_count} positions enrichies")
        print("=" * 80)
        print()
        print("💡 Dashboard: http://localhost:8889")
    else:
        print()
        print("ℹ️  Aucune position à enrichir")


if __name__ == '__main__':
    main()
