#!/usr/bin/env python3
"""
REAL-TIME signal generator - updates every 5 seconds.

This version generates signals from live order book data
and updates the display in near real-time.
"""

import subprocess
import time
from pathlib import Path
from datetime import datetime


def main():
    """Main loop with 5-second updates."""

    print("="*80)
    print("REAL-TIME SIGNAL GENERATOR (5-second updates)")
    print("="*80)
    print("\n⚡ Updating every 5 seconds for true real-time signals...")
    print("Press Ctrl+C to stop\n")

    update_count = 0
    start_time = time.time()

    try:
        while True:
            update_count += 1
            now = time.time()
            elapsed = now - start_time

            print(f"\n[{update_count}] Update at {datetime.now().strftime('%H:%M:%S')}")
            print(f"Running for: {int(elapsed)}s | Updates: {update_count} | Rate: {update_count/(elapsed/60):.1f}/min")
            print("-"*80)

            # Run multi-asset signal generator
            print("⚡ 1. Generating signals from order book...")
            result = subprocess.run(
                ['/home/ubuntu/.hermes/hermes-agent/.venv/bin/python3', 'generate_multi_asset_signals.py'],
                capture_output=True,
                text=True,
                cwd='/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/scripts'
            )

            if result.returncode != 0:
                print(f"  ✗ Error: {result.stderr}")
                time.sleep(5)
                continue

            # Generate single best signal
            print("⚡ 2. Selecting best signal (closest to price)...")
            start = time.time()
            result = subprocess.run(
                ['/home/ubuntu/.hermes/hermes-agent/.venv/bin/python3', 'generate_single_signal.py'],
                capture_output=True,
                text=True,
                cwd='/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/scripts'
            )
            signal_time = time.time() - start

            if result.returncode == 0:
                print(f"✓ Best signal selected (took {signal_time:.2f}s)")

                # Extract and show key info
                lines = result.stdout.split('\n')
                for line in lines:
                    if 'Best signal:' in line or 'Entry:' in line or 'Archived:' in line:
                        print(f"  {line.strip()}")
            else:
                print(f"  ✗ Error: {result.stderr}")

            # Show next update time
            next_update = datetime.fromtimestamp(time.time() + 5).strftime('%H:%M:%S')
            print(f"\n⏱️  Next update: {next_update} (in 5 seconds)...")

            # Wait 5 seconds (REAL-TIME!)
            time.sleep(5)

    except KeyboardInterrupt:
        elapsed = time.time() - start_time
        print("\n\n✓ Stopped by user")
        print(f"Total updates: {update_count}")
        print(f"Total runtime: {int(elapsed)}s ({int(elapsed/60)}m {int(elapsed%60)}s)")
        print(f"Average rate: {update_count/(elapsed/60):.1f} updates/minute")


if __name__ == "__main__":
    main()
