"""
Bot Runner Test - Run the full negoT8 bot with all features
Run this from anywhere: python test/bot_runner_test.py

Runs Bot A AND Bot B simultaneously so the full /pending cross-bot flow works:
  Phone A  →  /coordinate @userB  →  enters preferences
  Phone B  →  /pending            →  sees request, taps Accept
  Phone B  →  enters preferences  →  agents negotiate live
"""
import sys
import os
import asyncio

# Add backend to path so we can import modules
backend_path = os.path.join(os.path.dirname(__file__), '..', 'backend')
sys.path.insert(0, backend_path)

# Now import the bot creator and config
from config import TELEGRAM_BOT_TOKEN_A, TELEGRAM_BOT_TOKEN_B
import database as db

# Import bot after path is set
telegram_bots_path = os.path.join(backend_path, 'telegram-bots')
sys.path.insert(0, telegram_bots_path)

from bot import create_bot
from telegram import Update


async def setup_database():
    """Initialize database tables if needed."""
    print("🗄️  Initializing database...")
    await db.init_db()
    print("✅ Database ready!")


async def run_bots_async():
    """Start both Bot A and Bot B concurrently so pending_coordinations is shared."""
    bots = []

    if TELEGRAM_BOT_TOKEN_A:
        bot_a = create_bot(TELEGRAM_BOT_TOKEN_A)
        bots.append(("A", bot_a))
        print(f"✅ Bot A configured: {TELEGRAM_BOT_TOKEN_A[:20]}...")
    else:
        print("⚠️  TELEGRAM_BOT_TOKEN_A not set — skipping Bot A")

    if TELEGRAM_BOT_TOKEN_B:
        bot_b = create_bot(TELEGRAM_BOT_TOKEN_B)
        bots.append(("B", bot_b))
        print(f"✅ Bot B configured: {TELEGRAM_BOT_TOKEN_B[:20]}...")
    else:
        print("⚠️  TELEGRAM_BOT_TOKEN_B not set — skipping Bot B (only 1 bot)")

    if not bots:
        print("❌ No bot tokens found. Check your .env file.")
        return

    print(f"\n🚀 Launching {len(bots)} bot(s) in parallel...")
    print("=" * 60)
    print()

    # Initialize all bots and run them concurrently
    tasks = []
    for name, app in bots:
        await app.initialize()
        await app.start()
        print(f"▶️  Bot {name} is polling...")
        tasks.append(app.updater.start_polling(allowed_updates=Update.ALL_TYPES))

    await asyncio.gather(*tasks)


def main():
    """Run Bot A (and optionally Bot B) with full feature set."""
    print("=" * 60)
    print("🤖 Starting negoT8 Bots (Full Feature Set)")
    print("=" * 60)
    print()
    print("📋 Features enabled:")
    print("  • /start         — Welcome message")
    print("  • /personality   — Set agent negotiation style (5 types)")
    print("  • /coordinate @u — Start a coordination request (User A)")
    print("  • /pending       — View & accept incoming requests (User B)")
    print("  • /help          — View all commands")
    print()

    if not TELEGRAM_BOT_TOKEN_A and not TELEGRAM_BOT_TOKEN_B:
        print("❌ ERROR: No bot tokens found in environment!")
        print("   Make sure your .env file has TELEGRAM_BOT_TOKEN_A (and optionally _B) set.")
        return

    # Setup database
    asyncio.run(setup_database())

    print("🚀 Bots are now running... Press Ctrl+C to stop")
    print("=" * 60)
    print()

    try:
        asyncio.run(run_bots_async())
    except KeyboardInterrupt:
        print("\n\n👋 Bots stopped by user")
    except Exception as e:
        print(f"\n\n❌ Bot crashed: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()

