#!/usr/bin/env python3
"""
Update visualizer to show ONLY current price signals.

This changes the UI to focus on actionable opportunities.
"""

import json
from pathlib import Path


def update_visualizer_ui():
    """Update the HTML to use near-price filtered signals."""

    ui_file = Path("/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/outputs/multi_asset_visualizer.html")

    # Read the file
    with open(ui_file, 'r') as f:
        content = f.read()

    # Replace the signals file path
    content = content.replace(
        "const response = await fetch(`data/signals_${asset}.json`);",
        "const response = await fetch(`data/signals_${asset}_near_price.json`);"
    )

    # Add explanation about filtering
    stats_section = """
                <p style="text-align: center; margin-bottom: 20px; opacity: 0.8; font-size: 0.9em;">
                    ℹ️ Showing only signals within ±$5 of current price (actionable opportunities)
                </p>
    """

    # Insert after the subtitle
    content = content.replace(
        '<p class="subtitle">Real-time market microstructure analysis across multiple assets</p>',
        '<p class="subtitle">Real-time market microstructure analysis across multiple assets</p>' + stats_section
    )

    # Write back
    with open(ui_file, 'w') as f:
        f.write(content)

    print("✓ Updated visualizer to use near-price filtered signals")
    print("  Now shows ONLY actionable signals!")


def create_tighter_filter():
    """Create a much tighter filter (only ±$3 from price)."""

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

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

    signals = data['signals']

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

    # VERY tight filter: ±$3
    price_tolerance = 3.0

    tight_signals = [
        s for s in signals
        if abs(s['entry_price'] - current_price) <= price_tolerance
    ]

    print(f"\n📊 Current Price: ${current_price:.2f}")
    print(f"📌 Tight Filter: ±${price_tolerance}")
    print(f"✅ Signals near price: {len(tight_signals)}")
    print(f"❌ Filtered out: {len(signals) - len(tight_signals)}")

    # Show what we kept
    if tight_signals:
        print(f"\n✅ KEPT (within ±${price_tolerance} of ${current_price:.0f}):")
        for s in tight_signals[:20]:
            print(f"   ${s['entry_price']:.2f} - {s['type']} ({s['direction']}) - {s['confidence']} confidence")

    # Save tight filter
    output_file = gold_file.parent / "signals_xautusdt_near_price.json"

    output_data = {
        'metadata': {
            'generated_at': data['metadata']['generated_at'],
            'signal_count': len(tight_signals),
            'current_price': current_price,
            'price_tolerance': price_tolerance,
            'filtered_out': len(signals) - len(tight_signals),
            'filter_reason': 'Tight filter: Only signals within ±$3 of current price'
        },
        'signals': tight_signals
    }

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

    # Copy to UI directory
    import shutil
    ui_file = Path("/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/outputs/data/signals_xautusdt_near_price.json")
    shutil.copy(output_file, ui_file)

    print(f"\n✓ Saved tight-filter signals to: {output_file}")
    print(f"✓ Copied to UI directory")


def main():
    """Apply tight price filter."""

    print("="*80)
    print("APPLYING TIGHT PRICE FILTER")
    print("="*80)

    create_tighter_filter()
    update_visualizer_ui()

    print("\n" + "="*80)
    print("✓ DONE!")
    print("="*80)
    print("\n💡 What changed:")
    print("  BEFORE: 193 signals (price range $4539-4579)")
    print("  AFTER:  ~50 signals (price range ${:.0f}±$3)".format(
        json.loads(Path("/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/outputs/data/signals_xautusdt_near_price.json").read_text())['metadata']['current_price']
    ))
    print("\n🌐 Refresh the visualizer:")
    print("   http://localhost:8080/multi_asset_visualizer.html")
    print("\n   Now you'll see ONLY actionable signals near current price!")
    print("="*80)


if __name__ == "__main__":
    main()
