import { z } from 'zod';
import open from 'open';
import { getYouTubeClient } from '../youtube-client.js';
export const playPlaylistSchema = z.object({
videoIds: z.array(z.string()).optional().describe('Array of YouTube video IDs to play as a playlist'),
query: z.string().optional().describe('Search query to find and play videos (used if videoIds not provided)'),
maxResults: z.number().min(1).max(50).default(10).describe('Number of videos to play when using query (default: 10)'),
}).refine(
(data) => data.videoIds !== undefined || data.query !== undefined,
{ message: 'Either videoIds or query must be provided' }
);
export type PlayPlaylistInput = z.infer<typeof playPlaylistSchema>;
export interface PlayPlaylistResult {
success: boolean;
message: string;
playlistUrl?: string;
videoCount: number;
}
export async function playPlaylist(input: PlayPlaylistInput): Promise<PlayPlaylistResult> {
try {
const client = getYouTubeClient();
let videoIds: string[] = input.videoIds || [];
// If no videoIds provided, search for videos using the query
if (videoIds.length === 0 && input.query) {
const searchResults = await client.searchVideos({
query: input.query,
maxResults: input.maxResults,
});
if (searchResults.length === 0) {
return {
success: false,
message: `No videos found for "${input.query}"`,
videoCount: 0,
};
}
videoIds = searchResults.map((video) => video.videoId);
}
if (videoIds.length === 0) {
return {
success: false,
message: 'No video IDs provided and no query specified',
videoCount: 0,
};
}
// Generate playlist URL
const playlistUrl = client.generatePlaylistUrl(videoIds);
// Open in default browser
await open(playlistUrl);
return {
success: true,
message: `🎬 Playing ${videoIds.length} video${videoIds.length > 1 ? 's' : ''} in your browser`,
playlistUrl,
videoCount: videoIds.length,
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
return {
success: false,
message: `Failed to play videos: ${errorMessage}`,
videoCount: 0,
};
}
}
export function formatPlayResult(result: PlayPlaylistResult): string {
if (!result.success) {
return `❌ ${result.message}`;
}
const lines = [
result.message,
`🔗 URL: ${result.playlistUrl}`,
];
return lines.join('\n');
}