const { EmbedBuilder } = require('discord.js');

module.exports = {
  name: 'ready',
  once: true,
  
  async execute(client, supabase) {
    if (!supabase) return;
    
    setInterval(async () => {
      await checkStreams(client, supabase);
    }, 5 * 60 * 1000);
    
    setTimeout(async () => {
      await checkStreams(client, supabase);
    }, 30000);
    
    console.log('[Streams] Stream checker initialized (5 min interval)');
  }
};

async function checkStreams(client, supabase) {
  try {
    const { data: subs } = await supabase
      .from('stream_subscriptions')
      .select('*');
    
    if (!subs || subs.length === 0) return;
    
    const twitchSubs = subs.filter(s => s.platform === 'twitch');
    const youtubeSubs = subs.filter(s => s.platform === 'youtube');
    
    if (twitchSubs.length > 0) {
      await checkTwitchStreams(client, supabase, twitchSubs);
    }
    
    if (youtubeSubs.length > 0) {
      await checkYouTubeStreams(client, supabase, youtubeSubs);
    }
  } catch (err) {
    console.error('[Streams] Error checking streams:', err.message);
  }
}

async function checkTwitchStreams(client, supabase, subs) {
  const twitchClientId = process.env.TWITCH_CLIENT_ID;
  const twitchClientSecret = process.env.TWITCH_CLIENT_SECRET;
  
  if (!twitchClientId || !twitchClientSecret) {
    return;
  }
  
  try {
    const tokenRes = await fetch('https://id.twitch.tv/oauth2/token', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: `client_id=${twitchClientId}&client_secret=${twitchClientSecret}&grant_type=client_credentials`
    });
    
    if (!tokenRes.ok) return;
    const { access_token } = await tokenRes.json();
    
    const usernames = [...new Set(subs.map(s => s.username))];
    const chunkedUsernames = [];
    for (let i = 0; i < usernames.length; i += 100) {
      chunkedUsernames.push(usernames.slice(i, i + 100));
    }
    
    for (const chunk of chunkedUsernames) {
      const userQuery = chunk.map(u => `user_login=${u}`).join('&');
      const streamsRes = await fetch(`https://api.twitch.tv/helix/streams?${userQuery}`, {
        headers: {
          'Client-ID': twitchClientId,
          'Authorization': `Bearer ${access_token}`
        }
      });
      
      if (!streamsRes.ok) continue;
      const { data: liveStreams } = await streamsRes.json();
      
      const liveUsernames = liveStreams?.map(s => s.user_login.toLowerCase()) || [];
      
      for (const sub of subs.filter(s => chunk.includes(s.username))) {
        const isNowLive = liveUsernames.includes(sub.username.toLowerCase());
        const wasLive = sub.is_live;
        
        if (isNowLive && !wasLive) {
          const streamData = liveStreams.find(s => s.user_login.toLowerCase() === sub.username.toLowerCase());
          await sendNotification(client, supabase, sub, streamData, 'twitch');
          
          await supabase
            .from('stream_subscriptions')
            .update({ 
              is_live: true, 
              last_live_at: new Date().toISOString(),
              last_notified_at: new Date().toISOString()
            })
            .eq('id', sub.id);
        } else if (!isNowLive && wasLive) {
          await supabase
            .from('stream_subscriptions')
            .update({ is_live: false })
            .eq('id', sub.id);
        }
      }
    }
  } catch (err) {
    console.error('[Streams] Twitch check error:', err.message);
  }
}

async function checkYouTubeStreams(client, supabase, subs) {
  const youtubeApiKey = process.env.YOUTUBE_API_KEY;
  
  if (!youtubeApiKey) {
    return;
  }
  
  try {
    for (const sub of subs) {
      const searchRes = await fetch(
        `https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=${sub.username}&type=video&eventType=live&key=${youtubeApiKey}`
      );
      
      if (!searchRes.ok) {
        const handleRes = await fetch(
          `https://www.googleapis.com/youtube/v3/channels?part=snippet&forHandle=${sub.username}&key=${youtubeApiKey}`
        );
        if (handleRes.ok) {
          const { items } = await handleRes.json();
          if (items && items[0]) {
            const channelId = items[0].id;
            const liveRes = await fetch(
              `https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=${channelId}&type=video&eventType=live&key=${youtubeApiKey}`
            );
            if (liveRes.ok) {
              const { items: liveItems } = await liveRes.json();
              const isNowLive = liveItems && liveItems.length > 0;
              const wasLive = sub.is_live;
              
              if (isNowLive && !wasLive) {
                await sendNotification(client, supabase, sub, liveItems[0], 'youtube');
                await supabase
                  .from('stream_subscriptions')
                  .update({ 
                    is_live: true, 
                    last_live_at: new Date().toISOString(),
                    last_notified_at: new Date().toISOString()
                  })
                  .eq('id', sub.id);
              } else if (!isNowLive && wasLive) {
                await supabase
                  .from('stream_subscriptions')
                  .update({ is_live: false })
                  .eq('id', sub.id);
              }
            }
          }
        }
        continue;
      }
      
      const { items } = await searchRes.json();
      const isNowLive = items && items.length > 0;
      const wasLive = sub.is_live;
      
      if (isNowLive && !wasLive) {
        await sendNotification(client, supabase, sub, items[0], 'youtube');
        await supabase
          .from('stream_subscriptions')
          .update({ 
            is_live: true, 
            last_live_at: new Date().toISOString(),
            last_notified_at: new Date().toISOString()
          })
          .eq('id', sub.id);
      } else if (!isNowLive && wasLive) {
        await supabase
          .from('stream_subscriptions')
          .update({ is_live: false })
          .eq('id', sub.id);
      }
      
      await new Promise(r => setTimeout(r, 1000));
    }
  } catch (err) {
    console.error('[Streams] YouTube check error:', err.message);
  }
}

async function sendNotification(client, supabase, sub, streamData, platform) {
  try {
    const guild = client.guilds.cache.get(sub.guild_id);
    if (!guild) return;
    
    const channel = guild.channels.cache.get(sub.channel_id);
    if (!channel) return;
    
    let title, game, url, thumbnail;
    
    if (platform === 'twitch') {
      title = streamData.title || 'Live Stream';
      game = streamData.game_name || 'Unknown';
      url = `https://twitch.tv/${sub.username}`;
      thumbnail = streamData.thumbnail_url?.replace('{width}', '400').replace('{height}', '225');
    } else {
      title = streamData.snippet?.title || 'Live Stream';
      game = streamData.snippet?.channelTitle || sub.username;
      url = `https://youtube.com/watch?v=${streamData.id?.videoId}`;
      thumbnail = streamData.snippet?.thumbnails?.high?.url;
    }
    
    let message = sub.custom_message || '🔴 **{streamer}** is now live!\n{title}\n{url}';
    message = message
      .replace('{streamer}', sub.username)
      .replace('{title}', title)
      .replace('{game}', game)
      .replace('{url}', url);
    
    const embed = new EmbedBuilder()
      .setColor(platform === 'twitch' ? 0x9146ff : 0xff0000)
      .setTitle(`${sub.username} is now live!`)
      .setDescription(title)
      .setURL(url)
      .addFields(
        { name: 'Game/Category', value: game, inline: true },
        { name: 'Platform', value: platform.charAt(0).toUpperCase() + platform.slice(1), inline: true }
      )
      .setTimestamp();
    
    if (thumbnail) {
      embed.setImage(thumbnail);
    }
    
    await channel.send({ content: message, embeds: [embed] });
    console.log(`[Streams] Sent notification for ${sub.username} going live on ${platform}`);
  } catch (err) {
    console.error('[Streams] Notification send error:', err.message);
  }
}
