// api/check-song-status.ts
//
// Check the status of a song generation by clip IDs
// Returns audio URL and song URL when complete

export const config = { runtime: 'edge' };

const SUNO_HOST = (process.env.SUNO_BASE_URL ?? '').replace(/\/+$/, '');
const SUNO_KEY = process.env.SUNO_API_KEY;
const SUNO_SONG_URL_BASE = process.env.SUNO_SONG_URL_BASE || 'https://suno.com/song';

if (!SUNO_HOST || !SUNO_KEY) {
  throw new Error('SUNO_BASE_URL or SUNO_API_KEY is not set');
}

// Helper to call Suno API directly (server-side)
async function callSunoAPI(endpoint: string, method: string = 'GET', body?: any) {
  const url = `${SUNO_HOST}${endpoint}`;
  const headers: HeadersInit = {
    'Authorization': `Bearer ${SUNO_KEY}`,
    'Content-Type': 'application/json',
  };

  const response = await fetch(url, {
    method,
    headers,
    body: body ? JSON.stringify(body) : undefined,
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Suno API error ${response.status}: ${errorText}`);
  }

  return await response.json();
}

export default async function handler(req: Request): Promise<Response> {
  try {
    // Only accept POST requests
    if (req.method !== 'POST') {
      return new Response(
        JSON.stringify({ 
          error: 'Method Not Allowed', 
          message: 'This endpoint only accepts POST requests' 
        }),
        { 
          status: 405,
          headers: { 'Content-Type': 'application/json' }
        }
      );
    }

    // Parse JSON body
    const body = await req.json();
    const clipIds = body.clipIds || body.clip_id || body.clipId;

    if (!clipIds || !Array.isArray(clipIds) || clipIds.length === 0) {
      return new Response(
        JSON.stringify({ 
          error: 'Bad Request', 
          message: 'Missing or invalid "clipIds" array in request body' 
        }),
        { 
          status: 400,
          headers: { 'Content-Type': 'application/json' }
        }
      );
    }

    // Check status of clips
    const idsParam = clipIds.join(',');
    const response = await callSunoAPI(`/api/feed/v2?ids=${idsParam}`, 'GET');

    if (!response.clips || response.clips.length === 0) {
      return new Response(
        JSON.stringify({
          success: false,
          status: 'not_found',
          message: 'Clips not found',
        }),
        {
          status: 200,
          headers: { 'Content-Type': 'application/json' },
        }
      );
    }

    const clips = response.clips;
    const allComplete = clips.every((clip: any) => 
      clip.status === 'complete' || clip.status === 'error'
    );

    // If not all complete, return status
    if (!allComplete) {
      const statuses = clips.map((clip: any) => clip.status);
      return new Response(
        JSON.stringify({
          success: true,
          status: 'generating',
          clipStatuses: statuses,
          message: 'Song is still generating...',
        }),
        {
          status: 200,
          headers: { 'Content-Type': 'application/json' },
        }
      );
    }

    // Get the first completed clip
    const completedClip = clips.find((clip: any) => clip.status === 'complete');
    
    if (!completedClip) {
      const errorClip = clips.find((clip: any) => clip.status === 'error');
      const errorMsg = errorClip?.metadata?.error_message || 'Unknown error';
      return new Response(
        JSON.stringify({
          success: false,
          status: 'error',
          error: errorMsg,
        }),
        {
          status: 200,
          headers: { 'Content-Type': 'application/json' },
        }
      );
    }

    // Get audio URL and song page URL
    const audioUrl = completedClip.audio_url;
    const songUrl = `${SUNO_SONG_URL_BASE}/${completedClip.id}`;

    if (!audioUrl) {
      return new Response(
        JSON.stringify({
          success: false,
          status: 'error',
          error: 'No audio URL in completed clip',
        }),
        {
          status: 200,
          headers: { 'Content-Type': 'application/json' },
        }
      );
    }

    // Return success with audio URL
    return new Response(
      JSON.stringify({
        success: true,
        status: 'complete',
        audioUrl: audioUrl,
        songUrl: songUrl,
        title: completedClip.title || 'Generated Song',
        clipId: completedClip.id,
      }),
      {
        status: 200,
        headers: { 'Content-Type': 'application/json' },
      }
    );

  } catch (error) {
    console.error('❌ Error checking song status:', error);
    
    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
    
    return new Response(
      JSON.stringify({
        success: false,
        error: errorMessage,
      }),
      {
        status: 500,
        headers: { 'Content-Type': 'application/json' },
      }
    );
  }
}

