#!/usr/bin/env python3
"""
Cron job: Check for new order flow alerts and send to Telegram topic 2178.
Runs every 60 seconds.
"""

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


def send_to_telegram(message):
    """Send message to Telegram topic 2178 using send_message tool."""
    
    try:
        # Use hermes send_message command
        # Target: SC Portal topic 2178
        target = "telegram:SC Portal / topic 2178"
        
        cmd = [
            "hermes",
            "send_message",
            "--target", target,
            "--message", message
        ]
        
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=30
        )
        
        if result.returncode == 0:
            print(f"✅ Sent to Telegram topic 2178")
            return True
        else:
            print(f"❌ Failed: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"❌ Error: {e}")
        return False


def check_and_send_alerts():
    """Check for new alerts and send them."""

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

    if not alert_file.exists():
        return

    # Get file modification time
    alert_mtime = alert_file.stat().st_mtime
    now = time.time()

    # Only send if alert was updated in the last 2 minutes
    if now - alert_mtime > 120:
        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

    # Send alert
    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 120949...")
    print("-"*80)
    print(message)
    print("-"*80)

    success = send_to_telegram(message)

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

    print("="*80)


if __name__ == "__main__":
    check_and_send_alerts()
