#!/usr/bin/env python3
"""
Deployment script for AI News Digest Bot
Handles both Discord and Telegram deployment
"""

import os
import asyncio
import discord
from bot import AINewsBot
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# CE Discord Configuration
CE_GUILD_ID = 1467974388581273603
CE_GENERAL_CHANNEL = 1467975707106738290  # #curious-endeavor channel

class DiscordBotClient(discord.Client):
    """Discord client for the AI News Bot"""
    
    def __init__(self, news_bot, target_channel_id):
        intents = discord.Intents.default()
        intents.message_content = True
        super().__init__(intents=intents)
        self.news_bot = news_bot
        self.target_channel_id = target_channel_id
        
    async def on_ready(self):
        logger.info(f'Discord bot logged in as {self.user}')
        
        # Send daily digest
        await self.post_daily_digest()
        
        # Close connection after posting
        await self.close()
        
    async def post_daily_digest(self):
        """Generate and post daily digest"""
        try:
            # Generate digest
            result = await self.news_bot.run_daily_digest()
            
            if not result:
                logger.error("No digest generated")
                return
                
            # Get target channel
            channel = self.get_channel(self.target_channel_id)
            if not channel:
                logger.error(f"Channel {self.target_channel_id} not found")
                return
                
            # Split content if too long (Discord 2000 char limit)
            content = result['discord']
            if len(content) <= 2000:
                await channel.send(content)
                logger.info(f"Posted digest to #{channel.name}")
            else:
                # Split into multiple messages
                parts = self._split_message(content)
                for i, part in enumerate(parts):
                    await channel.send(part)
                    if i < len(parts) - 1:
                        await asyncio.sleep(1)  # Brief delay between messages
                logger.info(f"Posted digest in {len(parts)} parts to #{channel.name}")
                
        except Exception as e:
            logger.error(f"Error posting digest: {e}")
            
    def _split_message(self, content, max_length=1900):
        """Split message into Discord-friendly chunks"""
        if len(content) <= max_length:
            return [content]
            
        parts = []
        lines = content.split('\n')
        current_part = ""
        
        for line in lines:
            if len(current_part + line + '\n') <= max_length:
                current_part += line + '\n'
            else:
                if current_part:
                    parts.append(current_part.strip())
                    current_part = line + '\n'
                else:
                    # Line too long, force split
                    parts.append(line[:max_length])
                    current_part = line[max_length:]
                    
        if current_part:
            parts.append(current_part.strip())
            
        return parts

async def deploy_to_discord(channel_id=CE_GENERAL_CHANNEL):
    """Deploy bot to Discord and post daily digest"""
    
    # Check for Discord token
    discord_token = os.environ.get('DISCORD_BOT_TOKEN')
    if not discord_token:
        logger.error("DISCORD_BOT_TOKEN environment variable not set")
        return False
        
    # Create news bot
    news_bot = AINewsBot()
    
    # Create Discord client
    client = DiscordBotClient(news_bot, channel_id)
    
    try:
        # Run Discord bot (will post and then close)
        await client.start(discord_token)
        return True
    except Exception as e:
        logger.error(f"Discord deployment failed: {e}")
        return False

async def test_local():
    """Test digest generation locally without Discord"""
    logger.info("Testing local digest generation...")
    
    news_bot = AINewsBot()
    result = await news_bot.run_daily_digest()
    
    if result:
        print("\n" + "="*60)
        print("AI NEWS DIGEST TEST")
        print("="*60)
        print(result['discord'])
        print(f"\nTotal items: {len([item for items in result['items'].values() for item in items])}")
        print("="*60)
        return True
    else:
        print("No digest generated")
        return False

def setup_instructions():
    """Print setup instructions"""
    print("""
🤖 AI News Digest Bot - Deployment Instructions
===============================================

1. Discord Setup:
   - Create Discord bot at https://discord.com/developers/applications
   - Get bot token and set: export DISCORD_BOT_TOKEN="your_token_here"
   - Invite bot to CE Discord with permissions: Send Messages, Embed Links
   
2. Telegram Setup:
   - Message @BotFather on Telegram
   - Send: /newbot
   - Choose name: AI News Digest Bot
   - Choose username: ai_news_digest_bot (or similar)
   - Get token and set: export TELEGRAM_BOT_TOKEN="your_token_here"

3. Deployment:
   - Test local: python3 deploy.py --test
   - Deploy Discord: python3 deploy.py --discord
   - Deploy Telegram: python3 deploy.py --telegram
   
4. Cron Schedule (for daily automation):
   - Add to crontab: 0 8 * * * cd /path/to/bot && python3 deploy.py --discord
   - This posts daily at 8 AM UTC

Current Status: MVP ready, needs token configuration for live deployment
    """)

async def main():
    """Main deployment function"""
    import argparse
    
    parser = argparse.ArgumentParser(description='AI News Digest Bot Deployment')
    parser.add_argument('--test', action='store_true', help='Test local generation')
    parser.add_argument('--discord', action='store_true', help='Deploy to Discord')
    parser.add_argument('--telegram', action='store_true', help='Deploy to Telegram')
    parser.add_argument('--setup', action='store_true', help='Show setup instructions')
    
    args = parser.parse_args()
    
    if args.setup or (not args.test and not args.discord and not args.telegram):
        setup_instructions()
        return
        
    if args.test:
        success = await test_local()
        if success:
            logger.info("Local test successful - ready for deployment")
        return
        
    if args.discord:
        success = await deploy_to_discord()
        if success:
            logger.info("Discord deployment successful")
        return
        
    if args.telegram:
        logger.info("Telegram deployment not yet implemented")
        return

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