#!/usr/bin/env python3
"""
Add CFD price alignment to Gold signals.

Calculates CFD equivalent prices for Binance XAUTUSDT signals.
"""

import pandas as pd
import json
from pathlib import Path
from datetime import datetime
import statistics


def get_latest_cfd_price():
    """Get latest XAUUSD CFD price from MT5 data."""

    mt5_file = Path('/mnt/mt5/terminal/122160/Common/Files/Data/XAUUSD_PERIOD_M1_0.csv')

    if not mt5_file.exists():
        return None

    try:
        # Read MT5 CSV (UTF-16 LE)
        df = pd.read_csv(mt5_file,
                        encoding='utf-16-le',
                        names=['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume'])

        # Convert Close to numeric
        df['Close'] = pd.to_numeric(df['Close'], errors='coerce')

        # Get latest close price
        latest_close = df.iloc[-1]['Close']

        return float(latest_close)

    except Exception as e:
        print(f"Error reading CFD price: {e}")
        return None


def calculate_cfd_offset(binance_price, cfd_price):
    """Calculate the offset between Binance and CFD prices."""

    if cfd_price is None:
        return 0

    return cfd_price - binance_price


def update_gold_signals_with_cfd():
    """Update Gold signals to include CFD prices."""

    signals_file = Path('/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/outputs/data/signals_xautusdt.json')
    summary_file = Path('/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/outputs/data/realtime_summary_xautusdt.json')

    # Get current CFD price
    cfd_price = get_latest_cfd_price()

    print(f"Latest CFD price: ${cfd_price:.2f}" if cfd_price else "CFD price: unavailable")

    # Update signals file
    with open(signals_file) as f:
        signals_data = json.load(f)

    signals = signals_data['signals']

    if not signals:
        print("No signals to update")
        return

    # Get current Binance price
    entry_prices = [s['entry_price'] for s in signals]
    binance_price = statistics.median(entry_prices)

    # Calculate offset
    cfd_offset = calculate_cfd_offset(binance_price, cfd_price)

    print(f"Binance price: ${binance_price:.2f}")
    print(f"CFD offset: ${cfd_offset:.2f}")

    # Update each signal with CFD prices
    for signal in signals:
        signal['cfd'] = {
            'entry_price': round(signal['entry_price'] + cfd_offset, 2),
            'target_price': round(signal['target_price'] + cfd_offset, 2),
            'stop_price': round(signal['stop_price'] + cfd_offset, 2),
            'current_cfd_price': round(cfd_price, 2) if cfd_price else None
        }

    # Save updated signals
    with open(signals_file, 'w') as f:
        json.dump(signals_data, f, indent=2)

    print(f"✓ Updated {len(signals)} signals with CFD prices")

    # Update summary file
    with open(summary_file) as f:
        summary_data = json.load(f)

    # Add CFD info to summary
    summary_data['cfd'] = {
        'current_price': round(cfd_price, 2) if cfd_price else None,
        'offset_from_binance': round(cfd_offset, 2),
        'last_updated': datetime.now().isoformat()
    }

    # Update setups with CFD prices
    if 'setups' in summary_data:
        for setup in summary_data['setups']:
            setup['cfd_entry'] = round(setup['entry_price'] + cfd_offset, 2)
            setup['cfd_target'] = round(setup['target_price'] + cfd_offset, 2)
            setup['cfd_stop'] = round(setup['stop_price'] + cfd_offset, 2)

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

    print(f"✓ Updated summary with CFD prices")

    return cfd_price


if __name__ == "__main__":
    print("="*80)
    print("ADDING CFD PRICES TO GOLD SIGNALS")
    print("="*80)
    print()

    cfd_price = update_gold_signals_with_cfd()

    print()
    print("="*80)
    print("✓ DONE!")
    print("="*80)
    print(f"\nCFD price: ${cfd_price:.2f}" if cfd_price else "\nCFD price: unavailable")
    print("\nSignals now show both Binance and CFD prices!")
    print("Example:")
    print("  Entry: $4536.43 (CFD: $4525.75)")
    print("="*80)
