#!/usr/bin/env python3
"""
Generate single best signal per asset (closest to current price).

All historical signals will be stored for Graph RAG analysis.
Only the best signal (closest to price) is shown in the UI.
"""

import json
import statistics
from pathlib import Path
from datetime import datetime
import shutil


def generate_single_best_signal():
    """Generate only the best signal for each asset."""

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

    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)

        # Keep only high-quality signals
        quality_signals = [
            s for s in signals
            if s['confidence'] >= 0.85 and s['risk_reward'] >= 3.0
        ]

        if not quality_signals:
            print(f"{asset.upper()}: No quality signals")
            continue

        # Find signal closest to current price
        best_signal = min(quality_signals, key=lambda s: abs(s['entry_price'] - current_price))

        # Calculate distance
        distance = best_signal['entry_price'] - current_price

        # Create single signal summary
        summary = {
            'current_price': current_price,
            'best_setup': {
                'type': best_signal['type'],
                'direction': best_signal['direction'],
                'entry_price': best_signal['entry_price'],
                'target_price': best_signal['target_price'],
                'stop_price': best_signal['stop_price'],
                'risk_reward': best_signal['risk_reward'],
                'confidence': best_signal['confidence'],
                'distance_from_price': distance,
                'reason': best_signal.get('reason', ''),
                'note': best_signal.get('note', '')
            },
            'generated_at': datetime.now().isoformat(),
            'total_signals_analyzed': len(signals),
            'quality_signals_count': len(quality_signals)
        }

        # Add CFD prices for Gold
        if asset == 'xautusdt':
            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'])
                    cfd_offset = cfd_price - current_price

                    summary['best_setup']['cfd_entry'] = round(best_signal['entry_price'] + cfd_offset, 2)
                    summary['best_setup']['cfd_target'] = round(best_signal['target_price'] + cfd_offset, 2)
                    summary['best_setup']['cfd_stop'] = round(best_signal['stop_price'] + cfd_offset, 2)

                    summary['cfd'] = {
                        'current_price': round(cfd_price, 2),
                        'offset_from_binance': round(cfd_offset, 2)
                    }
            except Exception as e:
                print(f"  Warning: Could not read CFD price: {e}")

        # Determine sentiment
        if best_signal['direction'] == 'bullish':
            sentiment = "BULLISH 📈"
        else:
            sentiment = "BEARISH 📉"

        summary['sentiment'] = sentiment

        # Save single signal 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)

        # Calculate total stats
        bullish_count = sum(1 for s in quality_signals if s['direction'] == 'bullish')
        bearish_count = sum(1 for s in quality_signals if s['direction'] == 'bearish')

        print(f"{asset.upper()}: ${current_price:.2f} - {sentiment}")
        print(f"  Best signal: {best_signal['type']} - {best_signal['direction'].upper()}")
        print(f"  Entry: ${best_signal['entry_price']:.2f} (Distance: ${distance:.2f})")
        print(f"  Analyzed: {len(signals)} total → {len(quality_signals)} quality → 1 best")

        # Archive all signals for Graph RAG
        archive_dir = Path('/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/data/historical_signals')
        archive_dir.mkdir(exist_ok=True)

        # Archive with timestamp
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        archive_file = archive_dir / f'{asset}_signals_{timestamp}.json'

        with open(archive_file, 'w') as f:
            json.dump({
                'asset': asset,
                'timestamp': timestamp,
                'current_price': current_price,
                'signals_count': len(signals),
                'signals': signals
            }, f, indent=2)

        print(f"  Archived: {archive_file.name}")


def send_telegram_alert():
    """Send alert to Telegram topic 120949."""
    try:
        assets = ['btcusdt', 'ethusdt', 'xautusdt']
        
        # Format message
        lines = []
        lines.append("🎯 ORDER FLOW SIGNALS")
        lines.append(f"📊 {datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}")
        lines.append("")
        
        for asset in assets:
            summary_file = Path(f"/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/outputs/data/realtime_summary_{asset}.json")
            
            if not summary_file.exists():
                continue
            
            with open(summary_file) as f:
                data = json.load(f)
            
            current_price = data.get('current_price', 0)
            best_setup = data.get('best_setup', {})
            
            if not best_setup:
                continue
            
            direction = best_setup.get('direction', 'N/A').upper()
            stype = best_setup.get('type', 'N/A')
            
            if direction == 'BULLISH':
                emoji = "📈"
            elif direction == 'BEARISH':
                emoji = "📉"
            else:
                emoji = "➡️"
            
            lines.append(f"{emoji} {asset.upper()} @ ${current_price:,.2f} - {direction}")
            lines.append(f"   Type: {stype.upper()}")
            lines.append(f"   Entry: ${best_setup.get('entry_price', 0):,.2f}")
            lines.append(f"   Target: ${best_setup.get('target_price', 0):,.2f}")
            lines.append(f"   Stop: ${best_setup.get('stop_price', 0):,.2f}")
            lines.append(f"   RR: {best_setup.get('risk_reward', 0):.1f} (Conf: {int(best_setup.get('confidence', 0)*100)}%)")
            
            # Gold CFD alignment
            if 'cfd_entry' in best_setup:
                lines.append(f"   CFD: ${best_setup.get('cfd_entry', 0):,.2f}")
            
            lines.append("")
        
        lines.append("🌐 http://of.llm.astrona.me/outputs/main.html")
        
        message = "\n".join(lines)
        
        # Save to file for external script to send
        alert_file = Path("/tmp/order_flow_alert.txt")
        with open(alert_file, 'w') as f:
            f.write(message)
        
        print(f"\n📱 Telegram alert saved to: {alert_file}")
        print("   (Integrate with send_message tool to deliver)")
        
    except Exception as e:
        print(f"\n❌ Failed to prepare Telegram alert: {e}")


if __name__ == "__main__":
    print("="*80)
    print("SINGLE BEST SIGNAL GENERATOR")
    print("="*80)
    print("\nGenerating 1 best signal per asset (closest to current price)")
    print("All historical signals archived for Graph RAG analysis\n")
    print("-"*80)

    generate_single_best_signal()
    
    print("\n" + "="*80)
    print("✓ DONE!")
    print("="*80)
    print("\nUI shows only 1 signal per asset")
    print("Historical signals saved to: data/historical_signals/")
    print("\nReady for Graph RAG integration!")
    print("="*80)
    
    # Send Telegram alert
    send_telegram_alert()
