const API_KEY = process.env.YOUTUBE_API_KEY;
const CHANNEL_ID = process.env.YOUTUBE_CHANNEL_ID;

export async function getLatestVideos(maxResults = 4) {
  try {
    // Use search API to get latest videos (excludes Shorts by default)
    const searchResponse = await fetch(
      `https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=${CHANNEL_ID}&maxResults=${maxResults * 2}&order=date&type=video&key=${API_KEY}`
    );
    
    const searchData = await searchResponse.json();
    
    if (!searchData.items) {
      return [];
    }
    
    // Extract video IDs
    const videoIds = searchData.items.map(item => item.id.videoId).join(',');
    
    // Get video details
    const videoDetailsResponse = await fetch(
      `https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics,contentDetails&id=${videoIds}&key=${API_KEY}`
    );
    
    const videoDetailsData = await videoDetailsResponse.json();
    
    // Combine data and ensure we filter out any remaining Shorts
    const videos = searchData.items.map((item, index) => {
      const details = videoDetailsData.items.find(
        detail => detail.id === item.id.videoId
      );
      
      const duration = details?.contentDetails?.duration || '';
      const isShort = duration && isShortDuration(duration);
      
      return {
        id: item.id.videoId,
        title: item.snippet.title,
        description: item.snippet.description,
        thumbnail: item.snippet.thumbnails.medium?.url || item.snippet.thumbnails.default?.url,
        publishedAt: item.snippet.publishedAt,
        viewCount: details?.statistics?.viewCount || '0',
        duration: duration,
        isShort: isShort,
        url: `https://www.youtube.com/watch?v=${item.id.videoId}`
      };
    }).filter(video => !video.isShort) // Filter out Shorts
      .slice(0, maxResults); // Take only the requested number
    
    return videos;
    
  } catch (error) {
    console.error('Error fetching YouTube videos:', error);
    return [];
  }
}

// Helper function to check if duration indicates a Short
function isShortDuration(duration) {
  const match = duration.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
  const hours = parseInt(match[1] || 0);
  const minutes = parseInt(match[2] || 0);
  const seconds = parseInt(match[3] || 0);
  
  const totalSeconds = (hours * 3600) + (minutes * 60) + seconds;
  
  // Shorts are typically 60 seconds or less
  return totalSeconds <= 60;
}