#!/usr/bin/env python3
"""
Send order flow signals to Telegram topic 120949.
"""

import requests
import json
from pathlib import Path
from datetime import datetime


def send_to_telegram(message):
    """Send message to Telegram topic 120949."""
    
    # Read token from environment or use default
    import os
    bot_token = os.environ.get('TELEGRAM_BOT_TOKEN', '')
    
    # If no token, try to read from config file
    if not bot_token:
        config_file = Path.home() / '.hermes' / 'telegram_config.json'
        if config_file.exists():
            with open(config_file) as f:
                config = json.load(f)
                bot_token = config.get('bot_token', '')
    
    if not bot_token:
        print("❌ No Telegram bot token found!")
        print("   Set TELEGRAM_BOT_TOKEN environment variable or create ~/.hermes/telegram_config.json")
        return False
    
    # Target: telegram:-1003810904048:120949 (supergroup with topic)
    # Extract chat_id and topic_id
    chat_id = "-1003810904048"
    topic_id = 120949
    
    url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
    
    payload = {
        "chat_id": chat_id,
        "message_thread_id": topic_id,
        "text": message,
        "parse_mode": "HTML"
    }
    
    try:
        response = requests.post(url, json=payload, timeout=10)
        response.raise_for_status()
        
        result = response.json()
        if result.get('ok'):
            print("✅ Message sent to Telegram topic 120949!")
            return True
        else:
            print(f"❌ Telegram API error: {result}")
            return False
            
    except Exception as e:
        print(f"❌ Failed to send to Telegram: {e}")
        return False


def load_signal_summary():
    """Load the multi-asset signal summary."""
    
    summary_file = Path("/home/ubuntu/.hermes/workspace/projects/ORDER_FLOW_GRAPH/outputs/data/multi_asset_summary.json")
    
    if not summary_file.exists():
        print(f"❌ Summary file not found: {summary_file}")
        return None
    
    with open(summary_file) as f:
        return json.load(f)


def format_telegram_message(summary):
    """Format summary as Telegram message."""
    
    lines = []
    lines.append("🎯 <b>ORDER FLOW SIGNALS</b>")
    lines.append(f"📊 {datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}")
    lines.append("")
    
    for asset_data in summary.get('assets', []):
        asset = asset_data['asset']
        price = asset_data['current_price']
        direction = asset_data.get('direction', 'N/A').upper()
        
        # Emoji based on direction
        if direction == 'BULLISH':
            emoji = "📈"
        elif direction == 'BEARISH':
            emoji = "📉"
        else:
            emoji = "➡️"
        
        lines.append(f"{emoji} <b>{asset}</b> @ ${price:,.2f}")
        
        if 'best_setup' in asset_data:
            setup = asset_data['best_setup']
            lines.append(f"   Type: {setup.get('type', 'N/A').upper()}")
            lines.append(f"   Entry: ${setup.get('entry_price', 0):,.2f}")
            lines.append(f"   Target: ${setup.get('target_price', 0):,.2f}")
            lines.append(f"   Stop: ${setup.get('stop_price', 0):,.2f}")
            lines.append(f"   RR: {setup.get('risk_reward', 0):.1f} (Conf: {int(setup.get('confidence', 0)*100)}%)")
            
            # Gold CFD alignment
            if 'cfd_entry' in setup:
                lines.append(f"   CFD: ${setup.get('cfd_entry', 0):,.2f}")
        
        lines.append("")
    
    # Add footer
    lines.append("🌐 <a href=\"http://of.llm.astrona.me/outputs/main.html\">View Dashboard</a>")
    
    return "\n".join(lines)


def main():
    """Main function."""
    
    print("="*80)
    print("TELEGRAM ALERT SENDER")
    print("="*80)
    print()
    
    # Load signal summary
    print("1. Loading signal summary...")
    summary = load_signal_summary()
    
    if not summary:
        print("   ❌ No summary data available")
        return
    
    print(f"   ✅ Loaded {len(summary.get('assets', []))} assets")
    
    # Format message
    print("\n2. Formatting Telegram message...")
    message = format_telegram_message(summary)
    
    print("   ✅ Message formatted:")
    print("   " + "\n   ".join(message.split("\n")[:5]))
    print(f"   ... ({len(message)} chars)")
    
    # Send to Telegram
    print("\n3. Sending to Telegram topic 120949...")
    success = send_to_telegram(message)
    
    if success:
        print("\n✅ DONE! Signal alert sent to topic 120949")
    else:
        print("\n❌ Failed to send alert")
        print("   Check your Telegram bot token configuration")
    
    print("="*80)


if __name__ == "__main__":
    main()
