/**
 * Plainly.video API Integration
 * Documentation: https://docs.plainly.video/
 */

import { env } from '$env/dynamic/private';

// L'API v2 utilise https://api.plainlyvideos.com
const PLAINLY_API_BASE = 'https://api.plainlyvideos.com/api/v2';

interface PlainlyWebhook {
  url: string;
  onStateChange?: boolean;
  passThroughData?: Record<string, unknown>;
}

interface PlainlyRenderRequest {
  projectId: string;
  templateId: string;
  parameters: Record<string, string>;
  webhook?: PlainlyWebhook;
}

interface PlainlyRenderResponse {
  id: string;
  state: 'PENDING' | 'QUEUED' | 'IN_PROGRESS' | 'DONE' | 'FAILED' | 'INVALID' | 'CANCELLED' | 'THROTTLED';
  output?: string;
  error?: string;
}

/**
 * Lance un rendu vidéo sur Plainly
 */
export async function createRender(
  templateId: string,
  parameters: Record<string, string>,
  webhookUrl?: string,
  adId?: string
): Promise<PlainlyRenderResponse> {
  const requestBody: PlainlyRenderRequest = {
    projectId: env.PLAINLY_PROJECT_ID || '',
    templateId,
    parameters,
  };

  // Webhook doit être un objet, pas une string
  if (webhookUrl) {
    requestBody.webhook = {
      url: webhookUrl,
      onStateChange: true, // Recevoir les notifications à chaque changement d'état
      ...(adId && { passThroughData: { adId } }), // Passer l'adId pour pouvoir identifier l'annonce
    };
  }

  console.log('[Plainly] Creating render with:', JSON.stringify(requestBody, null, 2));

  // Plainly utilise Basic Auth avec l'API key
  const basicAuth = Buffer.from(`${env.PLAINLY_API_KEY || ''}:`).toString('base64');

  const response = await fetch(`${PLAINLY_API_BASE}/renders`, {
    method: 'POST',
    headers: {
      'Authorization': `Basic ${basicAuth}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(requestBody),
  });

  const responseText = await response.text();
  console.log('[Plainly] Response status:', response.status);
  console.log('[Plainly] Response body:', responseText);

  if (!response.ok) {
    let errorMessage = responseText;
    try {
      const parsed = JSON.parse(responseText);
      errorMessage = parsed.message || responseText;
    } catch {}
    throw new Error(errorMessage || `Plainly API error: ${response.status}`);
  }

  return JSON.parse(responseText);
}

/**
 * Récupère le statut d'un rendu
 */
export async function getRenderStatus(renderId: string): Promise<PlainlyRenderResponse> {
  const basicAuth = Buffer.from(`${env.PLAINLY_API_KEY || ''}:`).toString('base64');
  
  const response = await fetch(`${PLAINLY_API_BASE}/renders/${renderId}`, {
    headers: {
      'Authorization': `Basic ${basicAuth}`,
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: 'Erreur inconnue' }));
    throw new Error(error.message || `Plainly API error: ${response.status}`);
  }

  return response.json();
}

/**
 * Liste les templates disponibles dans le projet
 */
export async function listTemplates(): Promise<any[]> {
  const basicAuth = Buffer.from(`${env.PLAINLY_API_KEY || ''}:`).toString('base64');
  
  const response = await fetch(`${PLAINLY_API_BASE}/projects/${env.PLAINLY_PROJECT_ID || ''}/templates`, {
    headers: {
      'Authorization': `Basic ${basicAuth}`,
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: 'Erreur inconnue' }));
    throw new Error(error.message || `Plainly API error: ${response.status}`);
  }

  return response.json();
}

/**
 * Prépare les paramètres pour Plainly à partir du contenu d'une publicité
 */
export function prepareRenderParameters(
  adContent: {
    media_map?: Record<string, string | { url: string; thumbnail_url?: string }>;
    logo_url?: string | null;
    texts?: Record<string, string>;
  }
): Record<string, string> {
  const params: Record<string, string> = {};

  // Ajouter les médias
  if (adContent.media_map) {
    for (const [key, value] of Object.entries(adContent.media_map)) {
      if (value) {
        // media_map peut contenir soit une string URL, soit un objet {url, thumbnail_url}
        const mediaUrl = typeof value === 'string' ? value : value.url;
        if (mediaUrl) {
          params[key] = mediaUrl;
        }
      }
    }
  }

  // Ajouter le logo
  if (adContent.logo_url) {
    params['logo'] = adContent.logo_url;
  }

  // Ajouter les textes
  if (adContent.texts) {
    for (const [key, value] of Object.entries(adContent.texts)) {
      if (value) {
        params[key] = value;
      }
    }
  }

  return params;
}
