/**
 * Whisper STT 모듈 (yt-dlp 기반)
 * YouTube video_id를 받아 Whisper 서비스의 youtube-transcribe 엔드포인트를 호출합니다.
 */

import * as http from 'http';
import * as https from 'https';

// ── 로컬 Whisper GPU 서비스 URL ───────────────────────────────────────────
const LOCAL_WHISPER_URL = process.env.LOCAL_WHISPER_URL || 'http://localhost:8200';

// ── 내부 함수: youtube-transcribe 엔드포인트 호출 ─────────────────────────
function callYoutubeTranscribe(videoId: string): Promise<{text: string; source: string; duration: number} | null> {
    return new Promise((resolve) => {
        const whisperApiKey = process.env.WHISPER_API_KEY;
        const body = JSON.stringify({ video_id: videoId, language: 'ko' });

        const parsedUrl = new URL(`${LOCAL_WHISPER_URL}/v1/youtube-transcribe`);
        const isHttps = parsedUrl.protocol === 'https:';
        const reqModule = isHttps ? https : http;

        const options = {
            hostname: parsedUrl.hostname,
            port: parsedUrl.port || (isHttps ? 443 : 80),
            path: parsedUrl.pathname + parsedUrl.search,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': Buffer.byteLength(body),
                ...(whisperApiKey ? { 'X-API-Key': whisperApiKey } : {}),
            },
        };

        const req = reqModule.request(options, (res) => {
            const chunks: Buffer[] = [];
            res.on('data', (chunk: Buffer) => chunks.push(chunk));
            res.on('end', () => {
                const responseBody = Buffer.concat(chunks).toString('utf8');

                if (res.statusCode === 200) {
                    try {
                        const json = JSON.parse(responseBody);
                        const text: string = json.text ?? '';
                        const source: string = json.source ?? '';
                        const duration: number = typeof json.duration === 'number' ? json.duration : 0;
                        resolve({ text, source, duration });
                    } catch {
                        console.log(`  [Whisper] youtube-transcribe JSON 파싱 실패: ${responseBody.slice(0, 200)}`);
                        resolve(null);
                    }
                } else {
                    console.log(`  [Whisper] youtube-transcribe HTTP 오류 ${res.statusCode}: ${responseBody.slice(0, 200)}`);
                    resolve(null);
                }
            });
        });

        req.on('error', (err) => {
            console.log(`  [Whisper] youtube-transcribe 연결 오류 — ${err.message}`);
            resolve(null);
        });

        // 긴 영상 대응: 600초 타임아웃
        req.setTimeout(600000, () => {
            req.destroy();
            console.log('  [Whisper] youtube-transcribe 타임아웃 (600초)');
            resolve(null);
        });

        req.write(body);
        req.end();
    });
}

// ── 공개 API: Whisper STT 전사 ────────────────────────────────────────────
export async function whisperTranscribe(videoId: string): Promise<string | null> {
    try {
        console.log(`  [Whisper] ${videoId}: youtube-transcribe 엔드포인트 호출 중...`);
        const result = await callYoutubeTranscribe(videoId);
        if (result && result.text.trim().length > 0) {
            console.log(`  [Whisper] ${videoId}: 전사 완료 (${result.text.length}자, source=${result.source})`);
            return result.text;
        }
        console.log(`  [Whisper] ${videoId}: 전사 결과 없음`);
        return null;
    } catch (err: any) {
        console.error(`  [Whisper] ${videoId}: 예상치 못한 오류 — ${err?.message || err}`);
        return null;
    }
}
