#!/usr/bin/env python3
"""
Order flow alert sender - Sends alerts to Telegram topic 2178.
This script is called by cron every 60 seconds.
"""

import sys
import os
from pathlib import Path

# Add hermes-agent to path
sys.path.insert(0, '/home/ubuntu/.hermes/hermes-agent')

def send_alert_to_telegram():
    """Send alert to Telegram using the send_message tool."""

    alert_file = Path("/tmp/order_flow_alert.txt")
    sent_log = Path("/tmp/order_flow_alerts_sent.log")

    if not alert_file.exists():
        return

    # Read alert
    with open(alert_file) as f:
        message = f.read()

    if not message.strip():
        return

    # Check if we've already sent this alert
    if sent_log.exists():
        with open(sent_log) as f:
            last_message = f.read().strip()
            if last_message == message:
                # Already sent, skip
                return

    # Import send_message from hermes tools
    try:
        from tools.send_tools import send_message
        from datetime import datetime

        print("="*80)
        print("TELEGRAM ALERT SENDER")
        print("="*80)
        print(f"\n📊 {datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}")
        print("\n📱 Sending alert to topic 2178...")
        print("-"*80)
        print(message)
        print("-"*80)

        # Send to Telegram topic 2178
        result = send_message(
            action="send",
            target="telegram:SC Portal / topic 2178",
            message=message
        )

        if result.get('success'):
            # Log that we sent this message
            with open(sent_log, 'w') as f:
                f.write(message)
            print("\n✅ Alert sent successfully!")
        else:
            print(f"\n❌ Failed to send alert: {result}")

        print("="*80)

    except Exception as e:
        print(f"❌ Error sending alert: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    send_alert_to_telegram()
