#!/usr/bin/env python3
"""
Create REAL-TIME actionable summary.

Show ONLY setups near current price (±$5).
This is what you can actually trade RIGHT NOW.
"""

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


def create_realtime_summary():
    """Create summary of ONLY tradeable setups near current price."""

    signals_file = Path("/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/data/signals_tradeable.json")

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

    signals = data['signals']

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

    print("="*80)
    print("REAL-TIME ACTIONABLE SUMMARY")
    print("="*80)
    print(f"\n📊 Current Price: ${current_price:.2f}")
    print(f"📊 Time: {datetime.now().strftime('%H:%M:%S UTC')}")

    # Keep ONLY signals near current price (±$5)
    near_signals = [
        s for s in signals
        if abs(s['entry_price'] - current_price) <= 5.0
    ]

    print(f"\n📊 Signals near price (±$5): {len(near_signals)}")

    if len(near_signals) == 0:
        print("\n✅ No tradeable setups near current price")
        print("   Market is balanced - wait for a setup to develop")
        return None

    # Group by type and direction
    from collections import defaultdict
    setups = defaultdict(list)

    for s in near_signals:
        if s['confidence'] >= 0.85 and s['risk_reward'] >= 3.0:
            key = f"{s['type']}_{s['direction']}"
            setups[key].append(s)

    print(f"\n" + "="*80)
    print(f"ACTIONABLE SETUPS (Near ${current_price:.0f})")
    print("="*80)

    summary = {
        'current_price': current_price,
        'setups': [],
        'generated_at': datetime.now().isoformat(),
        'price_range': f"{current_price - 5:.0f} - {current_price + 5:.0f}"
    }

    if not setups:
        print("\n✅ No high-quality setups near current price")
        print(f"   Found {len(near_signals)} low-quality signals - ignoring")
        summary['message'] = 'No high-quality setups near current price'
    else:
        # Show best setup for each type/direction
        for key, sigs in sorted(setups.items()):
            best = max(sigs, key=lambda s: s['confidence'] * s['risk_reward'])

            stype, direction = key.split('_')

            # Distance from current price
            distance = best['entry_price'] - current_price
            distance_str = f"{'Above' if distance > 0 else 'Below'} by ${abs(distance):.2f}"

            print(f"\n🎯 {stype} - {direction.upper()}")
            print(f"   Entry: ${best['entry_price']:.2f} ({distance_str})")
            print(f"   Target: ${best['target_price']:.2f} (+${best['target_price'] - best['entry_price']:.2f})")
            print(f"   Stop: ${best['stop_price']:.2f} (-${best['entry_price'] - best['stop_price']:.2f})")
            print(f"   Risk-Reward: {best['risk_reward']}")
            print(f"   Confidence: {best['confidence']}")

            summary['setups'].append({
                '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': distance
            })

    # Count 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)

    print(f"\n" + "="*80)
    print("NEAR-PRICE SENTIMENT")
    print("="*80)
    print(f"\nBullish signals (≥85% conf, within ±$5): {bullish_count}")
    print(f"Bearish signals (≥85% conf, within ±$5): {bearish_count}")

    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 ↔️"

    print(f"\nNear-price sentiment: {sentiment}")

    summary['sentiment'] = sentiment
    summary['bullish_signals'] = bullish_count
    summary['bearish_signals'] = bearish_count

    # Save summary
    summary_file = Path("/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/outputs/data/realtime_summary.json")
    with open(summary_file, 'w') as f:
        json.dump(summary, f, indent=2)

    # Also copy to root
    root_summary = Path("/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/realtime_summary.json")
    with open(root_summary, 'w') as f:
        json.dump(summary, f, indent=2)

    print(f"\n" + "="*80)
    print("✓ Saved to:")
    print(f"  {summary_file}")
    print(f"  {root_summary}")

    print("\n" + "="*80)
    print("🌐 Refresh visualizer:")
    print("   http://localhost:8080/multi_asset_visualizer.html")
    print("="*80)

    return summary


def create_simple_telegram_summary():
    """Create simple text summary for Telegram."""

    summary_file = Path("/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/realtime_summary.json")

    if not summary_file.exists():
        print("No summary file found")
        return

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

    lines = []
    lines.append("⚡ ORDER FLOW - RIGHT NOW")
    lines.append("="*40)
    lines.append(f"Price: ${data['current_price']:.2f}")
    lines.append(f"Range: {data.get('price_range', 'N/A')}")
    lines.append(f"Sentiment: {data['sentiment']}")

    if data.get('message'):
        lines.append(f"\n✅ {data['message']}")
    elif data['setups']:
        lines.append(f"\nACTIONABLE SETUPS:")
        for setup in data['setups']:
            direction_emoji = "🐂" if setup['direction'] == 'bullish' else "🐻"
            lines.append(f"\n{direction_emoji} {setup['type'].upper()}")
            lines.append(f"   Entry: ${setup['entry_price']:.2f}")
            lines.append(f"   Target: ${setup['target_price']:.2f}")
            lines.append(f"   Stop: ${setup['stop_price']:.2f}")
            lines.append(f"   RR: {setup['risk_reward']} (Conf: {int(setup['confidence']*100)}%)")

    text = "\n".join(lines)

    # Save
    txt_file = Path("/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/outputs/realtime.txt")
    with open(txt_file, 'w') as f:
        f.write(text)

    print(f"\n📝 Telegram summary saved to: {txt_file}")
    print("\n" + text)

    return text


if __name__ == "__main__":
    create_realtime_summary()
    print("\n")
    create_simple_telegram_summary()
