#!/usr/bin/env python3
"""
Filter signals to show only those near current price.

This reduces noise by focusing on tradeable opportunities.
"""

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


def filter_signals_near_price(signals_file: Path, price_tolerance: float = 10.0):
    """Filter signals to only show those within tolerance of current price."""

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

    signals = data['signals']

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

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

    print(f"📊 Current Price: ${current_price:.2f}")
    print(f"📌 Price Tolerance: ±${price_tolerance}")
    print(f"📊 Total signals: {len(signals)}")

    # Filter: only show signals within tolerance
    tradeable_signals = [
        s for s in signals
        if abs(s['entry_price'] - current_price) <= price_tolerance
    ]

    filtered_out = len(signals) - len(tradeable_signals)

    print(f"✅ Tradeable signals (near price): {len(tradeable_signals)}")
    print(f"❌ Filtered out (far from price): {filtered_out}")

    # Show what we kept vs removed
    if tradeable_signals:
        print(f"\n✅ KEPT (near ${current_price:.0f}):")
        for s in tradeable_signals[:10]:
            print(f"   ${s['entry_price']:.2f} - {s['type']} ({s['direction']})")

    removed_signals = [s for s in signals if abs(s['entry_price'] - current_price) > price_tolerance]
    if removed_signals:
        print(f"\n❌ REMOVED (far from ${current_price:.0f}):")
        for s in removed_signals[:10]:
            distance = abs(s['entry_price'] - current_price)
            print(f"   ${s['entry_price']:.2f} - {s['type']} ({distance:.1f} away)")

    # Save filtered signals
    output_file = signals_file.parent / f"{signals_file.stem}_near_price.json"

    output_data = {
        'metadata': {
            'generated_at': datetime.now().isoformat(),
            'signal_count': len(tradeable_signals),
            'current_price': current_price,
            'price_tolerance': price_tolerance,
            'filtered_out': filtered_out,
            'filter_reason': 'Only signals near current price'
        },
        'signals': tradeable_signals
    }

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

    print(f"\n✓ Saved filtered signals to: {output_file}")

    return len(tradeable_signals)


def main():
    """Filter all asset signals."""

    print("="*80)
    print("FILTER SIGNALS NEAR CURRENT PRICE")
    print("="*80)

    # Gold signals
    gold_file = Path("/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/outputs/data/signals_xautusdt.json")

    print("\n🥇 GOLD (XAUTUSDT)")
    print("-"*80)

    if gold_file.exists():
        filter_signals_near_price(gold_file, price_tolerance=5.0)
    else:
        print("No signals file found")

    print("\n" + "="*80)
    print("✓ DONE!")
    print("="*80)
    print("\n💡 Now you have ONLY signals near current price!")
    print("   Much less noise, more actionable!")
    print("\n🌐 Refresh the visualizer to see filtered results:")
    print("   http://localhost:8080/multi_asset_visualizer.html")
    print("="*80)


if __name__ == "__main__":
    main()
