#!/usr/bin/env python3
"""
Simple Telegram Chat ID Finder

A more robust version that works better in server environments.
"""

import sys
import asyncio
import signal
from pathlib import Path

# Add src directory to Python path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))

try:
    from telegram import Bot
    from telegram.ext import Application, MessageHandler, filters
except ImportError:
    print("āŒ python-telegram-bot not installed!")
    print("šŸ’” Run: pip install python-telegram-bot")
    sys.exit(1)

# Global variables for graceful shutdown
running = True
found_ids = set()

def signal_handler(signum, frame):
    """Handle shutdown signals gracefully."""
    global running
    print(f"\nšŸ›‘ Stopping...")
    running = False

async def message_handler(update, context):
    """Handle incoming messages and show chat info."""
    global found_ids
    
    try:
        chat_id = update.effective_chat.id
        user = update.effective_user
        message_text = update.message.text if update.message else "No text"
        
        found_ids.add(chat_id)
        
        # Send response
        response = f"""
šŸŽÆ <b>Chat ID Found!</b>

šŸ†” <b>Chat ID:</b> <code>{chat_id}</code>
šŸ‘¤ <b>User:</b> {user.first_name} {user.last_name or ''}
šŸ“§ <b>Username:</b> @{user.username or 'None'}

āœ… <b>Add this to your .env file:</b>
<code>TELEGRAM_CHAT_ID={chat_id}</code>
        """
        
        await update.message.reply_text(response.strip(), parse_mode='HTML')
        
        # Print to console
        print(f"\nšŸŽ‰ SUCCESS! Chat ID: {chat_id}")
        print(f"šŸ‘¤ User: {user.first_name} {user.last_name or ''}")
        print(f"šŸ“§ Username: @{user.username or 'None'}")
        print(f"\nšŸ“‹ Add to .env file:")
        print(f"TELEGRAM_CHAT_ID={chat_id}")
        print(f"\nāœ… Press Ctrl+C to stop")
        
    except Exception as e:
        print(f"āŒ Error: {e}")

async def run_bot(token):
    """Run the bot to find Chat ID."""
    global running
    
    try:
        # Create application
        app = Application.builder().token(token).build()
        
        # Add message handler
        app.add_handler(MessageHandler(filters.ALL, message_handler))
        
        print("šŸ¤– Chat ID finder is running...")
        print("šŸ’¬ Send ANY message to your bot in Telegram")
        print("šŸ›‘ Press Ctrl+C when done\n")
        
        # Start the bot
        async with app:
            await app.start()
            await app.updater.start_polling()
            
            # Keep running until stopped
            while running:
                await asyncio.sleep(0.1)
                
            await app.updater.stop()
            
    except Exception as e:
        print(f"āŒ Bot error: {e}")
        raise

def main():
    """Main function."""
    global running, found_ids
    
    print("šŸ” Simple Telegram Chat ID Finder\n")
    
    # Set up signal handlers
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    # Get bot token
    token = input("šŸ¤– Enter your Telegram Bot Token: ").strip()
    
    if not token:
        print("āŒ No token provided!")
        return
    
    if ':' not in token:
        print("āŒ Invalid token format!")
        print("šŸ’” Should look like: 123456789:ABCdefGHIjklMNOPqrs")
        return
    
    print(f"\nāœ… Token looks valid!")
    print(f"šŸš€ Starting bot...\n")
    
    try:
        # Test the token first
        async def test_token():
            try:
                bot = Bot(token)
                me = await bot.get_me()
                print(f"šŸ¤– Bot: @{me.username} ({me.first_name})")
                return True
            except Exception as e:
                print(f"āŒ Invalid token: {e}")
                return False
        
        # Test token
        if not asyncio.run(test_token()):
            return
        
        # Run the bot
        asyncio.run(run_bot(token))
        
    except KeyboardInterrupt:
        pass
    except Exception as e:
        print(f"āŒ Error: {e}")
    finally:
        if found_ids:
            print(f"\nšŸ“‹ Found Chat IDs: {', '.join(map(str, found_ids))}")
            print(f"āœ… Add any of these to your .env file")
        else:
            print(f"\nāŒ No Chat IDs found")
            print(f"šŸ’” Make sure you sent a message to your bot!")

if __name__ == "__main__":
    main()