import { Telegraf, Context } from 'telegraf';
import { findUserByTelegramChatId, updateUserTelegram, findUserByBotToken, User } from '../models/user';
import { canMakeQuery, recordUsage } from '../models/usage';
import { querySportsData } from './sportsdata';

const BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN || '';

let bot: Telegraf | null = null;

export function initBot(): Telegraf {
  if (bot) return bot;
  
  bot = new Telegraf(BOT_TOKEN);
  
  // Start command - user links their account
  bot.command('start', async (ctx) => {
    const chatId = ctx.chat.id;
    const username = ctx.from?.username;
    const startPayload = ctx.message.text.split(' ')[1]; // /start <token>
    
    if (startPayload) {
      // User clicked link with token from website
      const user = await findUserByBotToken(startPayload);
      
      if (user) {
        await updateUserTelegram(user.id, username || '', chatId);
        
        await ctx.reply(
          `🦞 *Welcome to SportsClaw!*\n\n` +
          `Your account is now linked.\n\n` +
          `*Your Plan:* ${user.plan === 'free' ? 'Free (10 queries/day)' : user.plan}\n\n` +
          `Try these commands:\n` +
          `• \`nba odds tonight\`\n` +
          `• \`lebron james points\`\n` +
          `• \`nfl spreads\`\n\n` +
          `Just type what you want to know!`,
          { parse_mode: 'Markdown' }
        );
        return;
      }
    }
    
    // No token or invalid token
    await ctx.reply(
      `🦞 *SportsClaw Bot*\n\n` +
      `To use this bot, you need to link your account.\n\n` +
      `1. Go to https://sportsclaw.guru\n` +
      `2. Sign up or log in\n` +
      `3. Click "Connect Telegram"\n\n` +
      `Already have an account? Visit your dashboard to get the link.`,
      { parse_mode: 'Markdown' }
    );
  });
  
  // Help command
  bot.command('help', async (ctx) => {
    await ctx.reply(
      `🦞 *SportsClaw Commands*\n\n` +
      `*Odds & Lines:*\n` +
      `• \`nba odds tonight\`\n` +
      `• \`nfl spreads week 5\`\n` +
      `• \`mlb totals\`\n\n` +
      `*Player Props:*\n` +
      `• \`lebron james points\`\n` +
      `• \`mahomes passing yards\`\n` +
      `• \`ohtani strikeouts\`\n\n` +
      `*Matchups:*\n` +
      `• \`celtics vs lakers\`\n` +
      `• \`chiefs vs ravens\`\n\n` +
      `/usage - Check your daily usage\n` +
      `/plan - View your current plan`,
      { parse_mode: 'Markdown' }
    );
  });
  
  // Usage command
  bot.command('usage', async (ctx) => {
    const user = await findUserByTelegramChatId(ctx.chat.id);
    
    if (!user) {
      await ctx.reply('Account not linked. Visit https://sportsclaw.guru to connect.');
      return;
    }
    
    const usage = await canMakeQuery(user.id, user.plan);
    
    if (usage.limit === -1) {
      await ctx.reply(`📊 *Usage*\n\nPlan: ${user.plan}\nQueries: Unlimited ✨`, { parse_mode: 'Markdown' });
    } else {
      await ctx.reply(
        `📊 *Usage*\n\n` +
        `Plan: ${user.plan}\n` +
        `Today: ${usage.limit - usage.remaining}/${usage.limit} queries\n` +
        `Remaining: ${usage.remaining}`,
        { parse_mode: 'Markdown' }
      );
    }
  });
  
  // Plan command
  bot.command('plan', async (ctx) => {
    const user = await findUserByTelegramChatId(ctx.chat.id);
    
    if (!user) {
      await ctx.reply('Account not linked. Visit https://sportsclaw.guru to connect.');
      return;
    }
    
    const planInfo = {
      free: 'Free (10 queries/day)',
      weekly: 'Weekly ($9/week) - Unlimited',
      monthly: 'Monthly ($30/month) - Unlimited + Alerts',
    };
    
    await ctx.reply(
      `🦞 *Your Plan*\n\n` +
      `Current: ${planInfo[user.plan]}\n\n` +
      (user.plan === 'free' 
        ? 'Upgrade at https://sportsclaw.guru/signup?plan=monthly'
        : `Status: ${user.subscription_status}`),
      { parse_mode: 'Markdown' }
    );
  });
  
  // Handle all text messages as queries
  bot.on('text', async (ctx) => {
    const chatId = ctx.chat.id;
    const queryText = ctx.message.text;
    
    // Ignore commands
    if (queryText.startsWith('/')) return;
    
    // Find user
    const user = await findUserByTelegramChatId(chatId);
    
    if (!user) {
      await ctx.reply(
        '🦞 Account not linked!\n\nVisit https://sportsclaw.guru and click "Connect Telegram" to start.',
      );
      return;
    }
    
    // Check usage limits
    const usage = await canMakeQuery(user.id, user.plan);
    
    if (!usage.allowed) {
      await ctx.reply(
        `⚠️ *Daily Limit Reached*\n\n` +
        `You've used all ${usage.limit} free queries for today.\n\n` +
        `🔓 *Upgrade to Pro:*\n` +
        `• Unlimited queries\n` +
        `• Player props & analytics\n` +
        `• Real-time alerts\n\n` +
        `💰 Just $30/month or $9/week\n\n` +
        `👉 https://sportsclaw.guru/signup?plan=monthly`,
        { parse_mode: 'Markdown' }
      );
      return;
    }
    
    // Process query
    const startTime = Date.now();
    
    try {
      await ctx.sendChatAction('typing');
      
      const result = await querySportsData(queryText, user);
      const responseTime = Date.now() - startTime;
      
      // Record usage
      await recordUsage(user.id, result.type, queryText, responseTime);
      
      // Send response
      await ctx.reply(result.message, { parse_mode: 'Markdown' });
      
      // Show remaining for free users
      if (user.plan === 'free' && usage.remaining <= 3 && usage.remaining > 0) {
        await ctx.reply(
          `📊 *${usage.remaining - 1} queries left today*\n\n` +
          `💡 Upgrade to Pro for unlimited → $30/mo`,
          { parse_mode: 'Markdown' }
        );
      }
      
    } catch (error) {
      console.error('Query error:', error);
      await ctx.reply('Sorry, I couldn\'t process that query. Try rephrasing or use /help.');
    }
  });
  
  return bot;
}

export function startBot(): void {
  const b = initBot();
  b.launch();
  console.log('🤖 Telegram bot started');
  
  // Graceful shutdown
  process.once('SIGINT', () => b.stop('SIGINT'));
  process.once('SIGTERM', () => b.stop('SIGTERM'));
}

export function getBotUsername(): string {
  return process.env.TELEGRAM_BOT_USERNAME || 'sportsclaw_bot';
}
