#!/usr/bin/env python3
"""
Script de migration pour ajouter la colonne peak_pnl_percent à la table positions
"""

import sqlite3
import os
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def migrate_database():
    """Ajoute la colonne peak_pnl_percent si elle n'existe pas"""
    db_path = "crypto_trader.db"
    
    if not os.path.exists(db_path):
        logger.info(f"Base de données {db_path} n'existe pas - rien à migrer")
        return
    
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        # Vérifier si la colonne existe déjà
        cursor.execute("PRAGMA table_info(positions)")
        columns = [column[1] for column in cursor.fetchall()]
        
        if 'peak_pnl_percent' not in columns:
            logger.info("Ajout de la colonne peak_pnl_percent...")
            
            # Ajouter la colonne
            cursor.execute("ALTER TABLE positions ADD COLUMN peak_pnl_percent REAL DEFAULT 0.0")
            
            # Initialiser les valeurs existantes avec max(0, pnl_percent)
            cursor.execute("""
                UPDATE positions 
                SET peak_pnl_percent = CASE 
                    WHEN pnl_percent > 0 THEN pnl_percent 
                    ELSE 0.0 
                END
                WHERE status = 'ACTIVE'
            """)
            
            conn.commit()
            logger.info("Migration terminée avec succès")
        else:
            logger.info("La colonne peak_pnl_percent existe déjà")
        
        conn.close()
        
    except Exception as e:
        logger.error(f"Erreur lors de la migration: {e}")
        if conn:
            conn.rollback()
            conn.close()

if __name__ == "__main__":
    migrate_database()