import { openaiService } from '../services/openaiService';
import logger from './logger';

export interface TranscriptEntry {
  role?: string;
  message?: string;
  text?: string;
  time_in_call_secs?: number;
  translation?: string;
  [key: string]: any;
}

const TARGET_LANGUAGE_NAMES: Record<'ES' | 'EN', string> = {
  ES: 'Spanish',
  EN: 'English',
};

// Keep well under the model's context window per request.
const CHUNK_SIZE = 40;

/**
 * G1 — attach a per-entry `translation` to a conversation transcript, translated to
 * the bot's configured transcription language. Embedded directly in each entry
 * (no migration, alignment by construction), consistent with how F4 embeds the
 * translated summary in `aiAnalysis`.
 *
 * Reuses translations already present in a previous ingestion's `aiAnalysis.transcript`
 * (matched by exact `message` text) so re-ingestion — auto-ingest → webhook, or the
 * `?force=true` re-ingest — doesn't pay for the same translation twice and keeps
 * "one translation per conversation".
 *
 * Never throws: chunks that fail (OpenAI not configured, API error, malformed
 * response) are left untranslated rather than blocking the rest of ingestion.
 */
export async function attachTranscriptTranslations(
  transcriptArr: TranscriptEntry[],
  target: 'ES' | 'EN' | 'NONE' | null | undefined,
  existingAiAnalysis?: any
): Promise<TranscriptEntry[]> {
  if (!Array.isArray(transcriptArr) || transcriptArr.length === 0) return transcriptArr;
  if (!target || target === 'NONE') return transcriptArr;

  const previousByMessage = new Map<string, string>();
  const previousTranscript = existingAiAnalysis?.transcript;
  if (Array.isArray(previousTranscript)) {
    for (const entry of previousTranscript) {
      const msg = entry?.message ?? entry?.text;
      if (typeof msg === 'string' && typeof entry?.translation === 'string' && entry.translation.trim()) {
        previousByMessage.set(msg, entry.translation);
      }
    }
  }

  const result: TranscriptEntry[] = transcriptArr.map(entry => ({ ...entry }));
  const toTranslate: { index: number; text: string }[] = [];

  result.forEach((entry, index) => {
    const msg = entry.message ?? entry.text;
    if (typeof msg !== 'string' || !msg.trim()) return;

    const reused = previousByMessage.get(msg);
    if (reused) {
      entry.translation = reused;
    } else {
      toTranslate.push({ index, text: msg });
    }
  });

  if (toTranslate.length === 0) return result;

  const targetLanguageName = TARGET_LANGUAGE_NAMES[target];

  for (let i = 0; i < toTranslate.length; i += CHUNK_SIZE) {
    const chunk = toTranslate.slice(i, i + CHUNK_SIZE);
    const translations = await openaiService.translateTranscript(
      chunk.map(item => item.text),
      targetLanguageName
    );

    if (!translations) {
      logger.warn('⚠️ Skipping transcript translation chunk (discarded, left untranslated)', {
        chunkSize: chunk.length,
        chunkStart: i
      });
      continue;
    }

    chunk.forEach((item, j) => {
      const translated = translations[j];
      if (typeof translated === 'string' && translated.trim()) {
        result[item.index].translation = translated;
      }
    });
  }

  return result;
}
