#!/usr/bin/env python3
"""
Manual Trading Bot Launcher

A focused launcher for manual Hyperliquid trading via Telegram.
This script sets up comprehensive statistics tracking and phone-friendly controls.
"""

import logging
import asyncio
import sys
from datetime import datetime
from config import Config
from telegram_bot import TelegramTradingBot

# Set up logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=getattr(logging, Config.LOG_LEVEL)
)
logger = logging.getLogger(__name__)

def print_banner():
    """Print a nice startup banner."""
    banner = """
╔══════════════════════════════════════════════════════════════╗
║                    📱 MANUAL TRADING BOT                      ║
║                      for Hyperliquid                          ║
╠══════════════════════════════════════════════════════════════╣
║                                                              ║
║  🤖 Control your account from your phone via Telegram       ║
║  📊 Comprehensive trading statistics tracking               ║
║  📈 Real-time P&L monitoring                                ║
║  🛡️ Risk metrics (Sharpe, Sortino, VaR)                     ║
║  📱 Mobile-optimized interface                               ║
║                                                              ║
╚══════════════════════════════════════════════════════════════╝
    """
    print(banner)

def validate_setup():
    """Validate that everything is set up correctly."""
    print("🔍 Validating configuration...")
    
    # Check configuration
    if not Config.validate():
        print("❌ Configuration validation failed!")
        return False
    
    # Check Telegram setup
    if not Config.TELEGRAM_ENABLED:
        print("❌ Telegram is not enabled in configuration")
        print("💡 Please set TELEGRAM_ENABLED=true in your .env file")
        return False
    
    if not Config.TELEGRAM_BOT_TOKEN:
        print("❌ TELEGRAM_BOT_TOKEN not configured")
        print("💡 Please add your Telegram bot token to .env file")
        return False
    
    if not Config.TELEGRAM_CHAT_ID:
        print("❌ TELEGRAM_CHAT_ID not configured")
        print("💡 Please run: python get_telegram_chat_id.py")
        return False
    
    # Check Hyperliquid setup
    if not Config.HYPERLIQUID_PRIVATE_KEY:
        print("❌ HYPERLIQUID_PRIVATE_KEY not configured")
        print("💡 Please add your private key to .env file")
        return False
    
    print("✅ Configuration validation passed!")
    return True

def print_configuration():
    """Print current configuration."""
    print("\n📋 Current Configuration:")
    print(f"🌐 Network: {'Testnet' if Config.HYPERLIQUID_TESTNET else '🚨 MAINNET 🚨'}")
    print(f"📊 Trading Symbol: {Config.DEFAULT_TRADING_SYMBOL}")
    print(f"💰 Default Amount: {Config.DEFAULT_TRADE_AMOUNT}")
    print(f"💬 Telegram Bot: @{Config.TELEGRAM_BOT_TOKEN.split(':')[0] if Config.TELEGRAM_BOT_TOKEN else 'Not configured'}")
    print(f"🔑 Chat ID: {Config.TELEGRAM_CHAT_ID}")
    print(f"📈 Statistics: Enabled (saved to trading_stats.json)")
    
    if not Config.HYPERLIQUID_TESTNET:
        print("\n⚠️  WARNING: You are running on MAINNET!")
        print("💸 Real money will be used for trading!")
        response = input("Are you sure you want to continue? (type 'YES' to confirm): ")
        if response != 'YES':
            print("❌ Cancelled by user")
            return False
    
    return True

def print_usage_guide():
    """Print usage guide."""
    print("""
📱 How to Use Your Manual Trading Bot:

1️⃣ Start Telegram and find your bot
2️⃣ Send /start to see quick action buttons  
3️⃣ Use these commands for manual trading:

💼 ACCOUNT MONITORING:
   • /balance - Check your account balance
   • /positions - View open positions
   • /orders - See pending orders
   • /stats - Full trading statistics

🔄 MANUAL TRADING:
   • /buy 0.001 50000 - Buy 0.001 BTC at $50,000
   • /sell 0.001 55000 - Sell 0.001 BTC at $55,000
   • /trades - View recent trade history

📊 STATISTICS TRACKED:
   • 💰 Starting vs Current Balance
   • 📈 Total P&L and Return %
   • 🏆 Win Rate and Profit Factor
   • 📊 Sharpe & Sortino Ratios
   • 🎯 Max Drawdown and VaR
   • 🔄 Trade Count and Expectancy

🛡️ SAFETY FEATURES:
   • All trades require confirmation
   • Comprehensive logging
   • Real-time balance tracking
   • Risk metrics calculation
   • Order confirmations

⚠️  IMPORTANT:
   • Bot starts statistics tracking from first launch
   • All manual trades are automatically recorded
   • Statistics persist between bot restarts
   • Use /stats to see comprehensive performance metrics

Ready to start manual trading from your phone! 🚀
    """)

async def main():
    """Main function to start the manual trading bot."""
    try:
        print_banner()
        
        # Validate setup
        if not validate_setup():
            sys.exit(1)
        
        # Print configuration
        if not print_configuration():
            sys.exit(1)
        
        print_usage_guide()
        
        print("🚀 Starting Manual Trading Bot...")
        print("📱 Your phone controls are ready!")
        print("🔄 Statistics tracking initialized")
        print("⏰ Started at:", datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        print("\n💡 Open Telegram and send /start to your bot!")
        print("🛑 Press Ctrl+C to stop the bot\n")
        
        # Create and run the bot
        bot = TelegramTradingBot()
        await bot.run()
        
    except KeyboardInterrupt:
        print("\n👋 Manual Trading Bot stopped by user")
        print("📊 Your trading statistics have been saved")
        print("🔄 Restart anytime to continue tracking!")
    except Exception as e:
        logger.error(f"❌ Unexpected error: {e}")
        print(f"\n❌ Error: {e}")
        print("💡 Check your configuration and try again")

if __name__ == "__main__":
    asyncio.run(main())