#!/usr/bin/env python3
"""
Real-time signal generator - runs continuously.

Every 60 seconds, processes the latest order book data
and generates updated trading signals.
"""

import subprocess
import time
import json
from pathlib import Path
from datetime import datetime
import statistics


def generate_signals():
    """Run the signal generator script."""
    try:
        result = subprocess.run(
            ['/home/ubuntu/.hermes/hermes-agent/.venv/bin/python3', 'generate_multi_asset_signals.py'],
            capture_output=True,
            text=True,
            cwd='/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/scripts'
        )

        if result.returncode == 0:
            print(f"✓ Signals generated at {datetime.now().strftime('%H:%M:%S')}")
            return True
        else:
            print(f"✗ Error generating signals: {result.stderr}")
            return False

    except Exception as e:
        print(f"✗ Exception: {e}")
        return False


def create_realtime_summaries():
    """Create asset-specific realtime summaries."""

    assets = ['btcusdt', 'ethusdt', 'xautusdt']

    # Get CFD price for Gold
    cfd_price = None
    cfd_offset = 0
    if 'xautusdt' in assets:
        try:
            import pandas as pd
            mt5_file = Path('/mnt/mt5/terminal/122160/Common/Files/Data/XAUUSD_PERIOD_M1_0.csv')
            if mt5_file.exists():
                df = pd.read_csv(mt5_file, encoding='utf-16-le',
                               names=['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume'])
                df['Close'] = pd.to_numeric(df['Close'], errors='coerce')
                cfd_price = float(df.iloc[-1]['Close'])
                print(f"  CFD price: ${cfd_price:.2f}")
        except Exception as e:
            print(f"  Warning: Could not read CFD price: {e}")

    for asset in assets:
        signals_file = Path(f'/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/outputs/data/signals_{asset}.json')

        if not signals_file.exists():
            continue

        with open(signals_file) as f:
            data = json.load(f)

        signals = data['signals']

        if not signals:
            continue

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

        # Calculate CFD offset for Gold
        cfd_offset = 0
        if asset == 'xautusdt' and cfd_price:
            cfd_offset = cfd_price - current_price

        # Near-price signals
        tolerance = 5 if asset == 'xautusdt' else 10
        near_signals = [
            s for s in signals
            if abs(s['entry_price'] - current_price) <= tolerance
        ]

        # Quality signals
        quality_signals = [
            s for s in near_signals
            if s['confidence'] >= 0.85 and s['risk_reward'] >= 3.0
        ]

        # Best setups by type
        from collections import defaultdict
        setups = defaultdict(list)
        for s in quality_signals:
            key = f"{s['type']}_{s['direction']}"
            setups[key].append(s)

        best_setups = []
        for key, sigs in setups.items():
            best = max(sigs, key=lambda x: x['confidence'] * x['risk_reward'])
            stype, direction = key.split('_')

            setup_data = {
                'type': stype,
                'direction': direction,
                'entry_price': best['entry_price'],
                'target_price': best['target_price'],
                'stop_price': best['stop_price'],
                'risk_reward': best['risk_reward'],
                'confidence': best['confidence'],
                'distance_from_price': best['entry_price'] - current_price
            }

            # Add CFD prices for Gold
            if asset == 'xautusdt':
                setup_data['cfd_entry'] = round(best['entry_price'] + cfd_offset, 2)
                setup_data['cfd_target'] = round(best['target_price'] + cfd_offset, 2)
                setup_data['cfd_stop'] = round(best['stop_price'] + cfd_offset, 2)

            best_setups.append(setup_data)

        best_setups.sort(key=lambda x: x['confidence'] * x['risk_reward'], reverse=True)
        best_setups = best_setups[:5]

        # Sentiment
        bullish_count = sum(1 for s in near_signals if s['direction'] == 'bullish' and s['confidence'] >= 0.85)
        bearish_count = sum(1 for s in near_signals if s['direction'] == 'bearish' and s['confidence'] >= 0.85)

        if bearish_count > bullish_count * 1.5:
            sentiment = "BEARISH 📉"
        elif bullish_count > bearish_count * 1.5:
            sentiment = "BULLISH 📈"
        elif bearish_count > bullish_count:
            sentiment = "Slight bearish bias"
        elif bullish_count > bearish_count:
            sentiment = "Slight bullish bias"
        else:
            sentiment = "Neutral ↔️"

        summary = {
            'current_price': current_price,
            'setups': best_setups,
            'generated_at': datetime.now().isoformat(),
            'price_range': f"{current_price - tolerance:.0f} - {current_price + tolerance:.0f}",
            'sentiment': sentiment,
            'bullish_signals': bullish_count,
            'bearish_signals': bearish_count
        }

        # Add CFD info for Gold
        if asset == 'xautusdt' and cfd_price:
            summary['cfd'] = {
                'current_price': round(cfd_price, 2),
                'offset_from_binance': round(cfd_offset, 2)
            }

        if not best_setups:
            summary['message'] = 'No high-quality setups near current price'

        # Save summary
        output_file = Path(f'/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/outputs/data/realtime_summary_{asset}.json')
        with open(output_file, 'w') as f:
            json.dump(summary, f, indent=2)

        print(f"  {asset.upper()}: ${current_price:.2f} - {sentiment}")


def main():
    """Main loop."""

    print("="*80)
    print("REAL-TIME SIGNAL GENERATOR")
    print("="*80)
    print("\nUpdating signals every 60 seconds...")
    print("Press Ctrl+C to stop\n")

    update_count = 0

    try:
        while True:
            update_count += 1

            print(f"\n[{update_count}] Update at {datetime.now().strftime('%H:%M:%S')}")
            print("-"*80)

            # Generate signals from latest data
            if generate_signals():
                # Create summaries for UI
                create_realtime_summaries()
                print("✓ All assets updated")

            # Wait 60 seconds
            print("\n⏱️  Waiting 60 seconds...")
            time.sleep(60)

    except KeyboardInterrupt:
        print("\n\n✓ Stopped by user")
        print(f"Total updates: {update_count}")


if __name__ == "__main__":
    main()
