import { log } from './logger.js';

/**
 * Recording transcription / AI summarization integration.
 *
 * When the per-room "recording transcript" setting is enabled, Redlight POSTs
 * to ${TRANSCRIPTION_API_URL}/prompt with header `X-Api-Key: ${TRANSCRIPTION_API_KEY}`
 * as soon as the "video" format of a recording becomes available (delivered via
 * BBB's recording-ready callback). Leave both env vars empty to disable the
 * integration entirely.
 */

const TRANSCRIPTION_API_URL = process.env.TRANSCRIPTION_API_URL || '';
const TRANSCRIPTION_API_KEY = process.env.TRANSCRIPTION_API_KEY || '';

const DEFAULT_PROMPT = 'Summarise the key decisions made in this meeting.';

export function isTranscriptionEnabled() {
  return !!(TRANSCRIPTION_API_URL && TRANSCRIPTION_API_KEY);
}

/**
 * Request a summary/transcript for a recording. Never throws — failures are
 * logged and reported via the boolean return value.
 *
 * @param {object} opts
 * @param {string} opts.meetingId   Room UID / BBB meeting ID
 * @param {string} opts.recordingId BBB record ID
 * @param {string} [opts.prompt]    Optional custom prompt
 * @returns {Promise<boolean>} true if the request was accepted
 */
export async function requestTranscription({ meetingId, recordingId, prompt }) {
  if (!isTranscriptionEnabled()) {
    log.server.warn('Transcription request skipped: TRANSCRIPTION_API_URL or TRANSCRIPTION_API_KEY is not configured');
    return false;
  }

  const base = TRANSCRIPTION_API_URL.endsWith('/') ? TRANSCRIPTION_API_URL : `${TRANSCRIPTION_API_URL}/`;
  const url = new URL('prompt', base).toString();

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Api-Key': TRANSCRIPTION_API_KEY,
      },
      body: JSON.stringify({
        prompt: prompt || DEFAULT_PROMPT,
        meeting_id: meetingId,
        recording_id: recordingId,
      }),
      signal: AbortSignal.timeout(15_000),
    });

    if (!response.ok) {
      const body = await response.text().catch(() => '');
      log.server.error(`Transcription request failed: status=${response.status} body=${body.slice(0, 200)}`);
      return false;
    }

    log.server.info(`Transcription requested for recording ${recordingId} (meeting: ${meetingId})`);
    return true;
  } catch (err) {
    // undici wraps the real network error (ECONNREFUSED, ENOTFOUND, timeout, …)
    // in err.cause — surface it, "fetch failed" alone is undiagnosable.
    const cause = err.cause ? ` (${err.cause.code || ''} ${err.cause.message || ''})`.trimEnd() : '';
    log.server.error(`Transcription request to ${url} failed: ${err.message}${cause}`);
    return false;
  }
}
