from telethon import TelegramClient, events
import asyncio
import sys
import logging

# Set up logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)
logger = logging.getLogger(__name__)

# API credentials
api_id = 29007504
api_hash = '877e958822f299acd9d72729b9507cd2'

# Create the client with connection retries
client = TelegramClient('my_session', api_id, api_hash, 
    connection_retries=5,
    retry_delay=1
)

async def send_telegram_message(message_text):
    try:
        # Connect to Telegram
        await client.start()
        
        # Print basic info
        me = await client.get_me()
        logger.info(f'Connected as {me.first_name} ({me.username})')
        
        # Send message to group
        group_id = 5444240738
        try:
            # Check message is not empty
            if not message_text:
                raise ValueError("Message text cannot be empty")
                
            # Send message with retry logic
            for attempt in range(3):
                try:
                    await client.send_message(group_id, message_text)
                    logger.info('Message sent successfully!')
                    return True
                except Exception as e:
                    if attempt == 2:  # Last attempt
                        raise
                    logger.warning(f'Attempt {attempt + 1} failed, retrying...')
                    await asyncio.sleep(2)
                    
        except ValueError as ve:
            logger.error(f"Validation error: {ve}")
            return False
        except Exception as e:
            logger.error(f'Error sending message: {e}')
            return False
            
    except Exception as e:
        logger.error(f'Connection error: {e}')
        return False
    finally:
        await client.disconnect()

# Main function to be called from PHP
async def main():
    # Get message from command line args
    if len(sys.argv) < 2:
        logger.error("No message provided")
        return False
        
    message = sys.argv[1]
    return await send_telegram_message(message)

# Run the main function
if __name__ == '__main__':
    success = asyncio.run(main())
    sys.exit(0 if success else 1)
