#!/usr/bin/env python3
"""
Create a SMART signal summary.

Instead of showing 10 nearly-identical signals, show:
1. The BEST setup (highest quality)
2. Why it's a good setup
3. Clear entry/stop/target

This is MUCH more useful than 193 noise signals.
"""

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


def create_smart_summary():
    """Create a clear, actionable market summary."""

    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)

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

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

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

    # Find BEST setup for each type/direction
    print(f"\n" + "="*80)
    print("BEST SETUPS")
    print("="*80)

    summary = {
        'current_price': current_price,
        'setups': [],
        'generated_at': datetime.now().isoformat()
    }

    for key, sigs in sorted(setups.items()):
        if not sigs:
            continue

        # Get best signal (by confidence × rr)
        best = max(sigs, key=lambda s: s['confidence'] * s['risk_reward'])

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

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

        # Show what makes it special
        print(f"   📊 Order Book Context:")
        print(f"      BID volume: {best.get('order_book', {}).get('bid_volume', 'N/A')}")
        print(f"      ASK volume: {best.get('order_book', {}).get('ask_volume', 'N/A')}")

        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']
        })

    # Overall market sentiment
    print(f"\n" + "="*80)
    print("MARKET SENTIMENT")
    print("="*80)

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

    print(f"\nBullish signals (≥85% conf): {bullish_count}")
    print(f"Bearish signals (≥85% conf): {bearish_count}")

    if bearish_count > bullish_count * 2:
        sentiment = "STRONGLY BEARISH 🐻"
    elif bullish_count > bearish_count * 2:
        sentiment = "STRONGLY BULLISH 🐂"
    elif bearish_count > bullish_count:
        sentiment = "Bearish bias 📉"
    elif bullish_count > bearish_count:
        sentiment = "Bullish bias 📈"
    else:
        sentiment = "Neutral ↔️"

    print(f"\nOverall: {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/market_summary.json")
    with open(summary_file, 'w') as f:
        json.dump(summary, f, indent=2)

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

    print(f"\n" + "="*80)
    print("✓ Saved summary 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_text_summary():
    """Create a simple text summary for Telegram."""

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

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

    lines = []
    lines.append("📊 ORDER FLOW SUMMARY")
    lines.append("="*50)
    lines.append(f"Price: ${data['current_price']:.2f}")
    lines.append(f"Sentiment: {data['sentiment']}")
    lines.append("")
    lines.append("BEST SETUPS:")

    for setup in data['setups']:
        lines.append(f"\n🎯 {setup['type']} - {setup['direction'].upper()}")
        lines.append(f"   Entry: ${setup['entry_price']:.2f}")
        lines.append(f"   Target: ${setup['target_price']:.2f} (RR: {setup['risk_reward']})")
        lines.append(f"   Stop: ${setup['stop_price']:.2f}")

    text = "\n".join(lines)

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

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


if __name__ == "__main__":
    create_smart_summary()
    print("\n")
    create_simple_text_summary()
