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
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
// ---------------------------------------------------------------------------
// Transcript Tool -- YouTube URL to transcript (FIXED)
// ---------------------------------------------------------------------------
// Fix: The YouTube API fallback was silently producing empty content.
// This version uses proper HTTPS with cookies/consent bypass and robust
// caption extraction with multiple fallback strategies.
// ---------------------------------------------------------------------------

import { spawn, execSync } from 'child_process';
import fs from 'fs';
import path from 'path';
import https from 'https';
import http from 'http';
import os from 'os';
import type { ToolRegistry, ToolParams, ToolResult, ProgressEmitter } from '../toolRegistry';

const OUTPUT_DIR = path.join(__dirname, '..', '..', 'output');

export function register(registry: ToolRegistry): void {
    registry.register({
        name: 'transcript_tool',
        description: 'Extract transcript/subtitles from a YouTube video URL.',
        syntax: 'use <transcript_tool> <youtube-url>',
        pattern: /use\s+<transcript_tool>\s+(?<url>https?:\/\/(?:www\.)?(?:youtube\.com\/watch\?v=|youtu\.be\/)[\w-]+[^\s]*)/i,
        mock: false,

        async execute(params: ToolParams, emitProgress: ProgressEmitter): Promise<ToolResult> {
            const url = params.url || (params.captures && params.captures[0]);
            if (!url) throw new Error('No URL provided.');

            emitProgress('Extracting video ID...');
            const videoId = extractVideoId(url as string);
            if (!videoId) throw new Error('Invalid YouTube URL.');

            if (!fs.existsSync(OUTPUT_DIR)) {
                fs.mkdirSync(OUTPUT_DIR, { recursive: true });
            }

            emitProgress(`Video ID: ${videoId}`);

            // Strategy 1: Try yt-dlp (search PATH + Python Scripts)
            const ytdlpPath = await findYtdlp(emitProgress);
            if (ytdlpPath) {
                emitProgress(`yt-dlp found at: ${ytdlpPath}`);
                try {
                    const result = await fetchWithYtdlp(ytdlpPath, url as string, videoId, emitProgress);
                    if (result.transcript && (result.transcript as string).trim().length > 0) {
                        return result;
                    }
                    emitProgress('yt-dlp returned empty subtitles. Trying fallback...');
                } catch (err: any) {
                    emitProgress(`yt-dlp failed: ${err.message}. Trying fallback...`);
                }
            } else {
                emitProgress('yt-dlp not found. Using YouTube API fallback...');
            }

            // Strategy 2: YouTube innertube API
            try {
                const result = await fetchWithInnertube(videoId, emitProgress);
                if (result.transcript && (result.transcript as string).trim().length > 0) {
                    return result;
                }
                emitProgress('Innertube returned empty. Trying page scrape...');
            } catch (err: any) {
                emitProgress(`Innertube failed: ${err.message}. Trying page scrape...`);
            }

            // Strategy 3: Direct page scrape for captions
            try {
                const result = await fetchFromPage(videoId, emitProgress);
                if (result.transcript && (result.transcript as string).trim().length > 0) {
                    return result;
                }
            } catch (err: any) {
                emitProgress(`Page scrape failed: ${err.message}`);
            }

            throw new Error('Could not extract transcript. The video may not have captions, or YouTube blocked the request. Install yt-dlp for best results: pip install yt-dlp');
        },
    });
}

function extractVideoId(url: string): string | null {
    const patterns = [/[?&]v=([\w-]{11})/, /youtu\.be\/([\w-]{11})/, /embed\/([\w-]{11})/];
    for (const p of patterns) {
        const m = url.match(p);
        if (m) return m[1];
    }
    return null;
}

// --- Find yt-dlp: search PATH, Python Scripts dirs, pip locations ---
async function findYtdlp(emitProgress: ProgressEmitter): Promise<string | null> {
    const isWin = process.platform === 'win32';
    const exe = isWin ? 'yt-dlp.exe' : 'yt-dlp';

    // 1. Check if on PATH
    const onPath = await checkCommand('yt-dlp');
    if (onPath) return 'yt-dlp';

    emitProgress('yt-dlp not on PATH. Searching Python Scripts directories...');

    // 2. Search common Python Scripts locations (Windows)
    const home = os.homedir();
    const candidateDirs: string[] = [];

    if (isWin) {
        // Standard pip install locations
        candidateDirs.push(
            path.join(home, 'AppData', 'Local', 'Programs', 'Python', 'Python313', 'Scripts'),
            path.join(home, 'AppData', 'Local', 'Programs', 'Python', 'Python312', 'Scripts'),
            path.join(home, 'AppData', 'Local', 'Programs', 'Python', 'Python311', 'Scripts'),
            path.join(home, 'AppData', 'Local', 'Programs', 'Python', 'Python310', 'Scripts'),
            path.join(home, 'AppData', 'Roaming', 'Python', 'Python313', 'Scripts'),
            path.join(home, 'AppData', 'Roaming', 'Python', 'Python312', 'Scripts'),
            path.join(home, 'AppData', 'Roaming', 'Python', 'Python311', 'Scripts'),
        );

        // Microsoft Store Python (the location shown in user's pip warning)
        try {
            const packagesDir = path.join(home, 'AppData', 'Local', 'Packages');
            if (fs.existsSync(packagesDir)) {
                const entries = fs.readdirSync(packagesDir);
                for (const entry of entries) {
                    if (entry.startsWith('PythonSoftwareFoundation.Python')) {
                        // Search recursively for Scripts dir
                        const localCache = path.join(packagesDir, entry, 'LocalCache', 'local-packages');
                        if (fs.existsSync(localCache)) {
                            const pyDirs = fs.readdirSync(localCache).filter(d => d.startsWith('Python'));
                            for (const pyDir of pyDirs) {
                                candidateDirs.push(path.join(localCache, pyDir, 'Scripts'));
                            }
                        }
                    }
                }
            }
        } catch { }

        // Also try pip show to find the scripts directory
        try {
            const pipOutput = execSync('pip show yt-dlp 2>nul', { encoding: 'utf-8', timeout: 5000 });
            const locMatch = pipOutput.match(/Location:\s*(.+)/i);
            if (locMatch) {
                const sitePackages = locMatch[1].trim();
                // Scripts is typically a sibling of the site-packages dir
                const scriptsDir = path.join(path.dirname(sitePackages), 'Scripts');
                candidateDirs.unshift(scriptsDir); // prioritize
            }
        } catch { }

        // Try python -m pip show
        try {
            const pipOutput = execSync('python -m pip show yt-dlp 2>nul', { encoding: 'utf-8', timeout: 5000 });
            const locMatch = pipOutput.match(/Location:\s*(.+)/i);
            if (locMatch) {
                const sitePackages = locMatch[1].trim();
                const scriptsDir = path.join(path.dirname(sitePackages), 'Scripts');
                candidateDirs.unshift(scriptsDir);
            }
        } catch { }
    } else {
        // Linux/macOS
        candidateDirs.push(
            path.join(home, '.local', 'bin'),
            '/usr/local/bin',
            '/usr/bin',
        );
    }

    // Check each candidate
    for (const dir of candidateDirs) {
        const fullPath = path.join(dir, exe);
        if (fs.existsSync(fullPath)) {
            emitProgress(`Found yt-dlp at: ${fullPath}`);
            // Verify it works
            const works = await checkCommand(`"${fullPath}"`);
            if (works) return `"${fullPath}"`;
        }
    }

    // 3. Last resort: try python -m yt_dlp
    const pyModule = await checkCommand('python -m yt_dlp');
    if (pyModule) {
        emitProgress('Found yt-dlp as Python module.');
        return 'python -m yt_dlp';
    }

    return null;
}

function checkCommand(cmd: string): Promise<boolean> {
    return new Promise((resolve) => {
        const proc = spawn(cmd, ['--version'], { shell: true });
        let resolved = false;
        const timeout = setTimeout(() => { if (!resolved) { resolved = true; resolve(false); try { proc.kill(); } catch { } } }, 5000);
        proc.on('close', (code) => { if (!resolved) { resolved = true; clearTimeout(timeout); resolve(code === 0); } });
        proc.on('error', () => { if (!resolved) { resolved = true; clearTimeout(timeout); resolve(false); } });
    });
}

// --- Strategy 1: yt-dlp ---
function fetchWithYtdlp(ytdlpCmd: string, url: string, videoId: string, emitProgress: ProgressEmitter): Promise<ToolResult> {
    return new Promise((resolve, reject) => {
        const outTemplate = path.join(OUTPUT_DIR, videoId);

        // Build the full command string
        const cmdLine = `${ytdlpCmd} --write-auto-sub --write-sub --sub-lang en,en-US,en-GB --skip-download --sub-format vtt/srt/best -o "${outTemplate}" "${url}"`;

        const child = spawn(cmdLine, [], { shell: true });
        let stderr = '';

        child.stdout?.on('data', (chunk: Buffer) => emitProgress(chunk.toString().trim()));
        child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString(); });

        child.on('close', (code) => {
            if (code !== 0) return reject(new Error(`yt-dlp exited ${code}: ${stderr}`));

            // Find generated subtitle files
            const files = fs.readdirSync(OUTPUT_DIR).filter((f) =>
                f.startsWith(videoId) && (f.endsWith('.vtt') || f.endsWith('.srt'))
            );
            if (!files.length) return reject(new Error('No subtitle file generated.'));

            const subContent = fs.readFileSync(path.join(OUTPUT_DIR, files[0]), 'utf-8');
            const text = files[0].endsWith('.srt') ? parseSrt(subContent) : parseVtt(subContent);
            const fname = `${videoId}-transcript.txt`;
            fs.writeFileSync(path.join(OUTPUT_DIR, fname), text, 'utf-8');

            emitProgress(`Transcript saved: ${fname} (${text.length} chars)`);
            resolve({ transcript: text, downloadUrl: `/api/download/${fname}`, filename: fname, method: 'yt-dlp' });
        });

        child.on('error', reject);
    });
}

// --- Strategy 2: YouTube Innertube API ---
async function fetchWithInnertube(videoId: string, emitProgress: ProgressEmitter): Promise<ToolResult> {
    emitProgress('Fetching via YouTube Innertube API...');

    const body = JSON.stringify({
        context: {
            client: {
                clientName: 'WEB',
                clientVersion: '2.20240101.00.00',
                hl: 'en',
                gl: 'US',
            },
        },
        videoId: videoId,
    });

    const responseText = await httpPost(
        'https://www.youtube.com/youtubei/v1/get_transcript?prettyPrint=false',
        body,
        { 'Content-Type': 'application/json' }
    );

    // Parse the innertube transcript response
    const lines: string[] = [];
    try {
        const data = JSON.parse(responseText);
        const actions = data?.actions;
        if (actions) {
            for (const action of actions) {
                const segments = action?.updateEngagementPanelAction?.content?.transcriptRenderer
                    ?.body?.transcriptBodyRenderer?.cueGroups;
                if (segments) {
                    for (const seg of segments) {
                        const cues = seg?.transcriptCueGroupRenderer?.cues;
                        if (cues) {
                            for (const cue of cues) {
                                const text = cue?.transcriptCueRenderer?.cue?.simpleText;
                                if (text) lines.push(text.trim());
                            }
                        }
                    }
                }
            }
        }
    } catch {
        // JSON parse failed
    }

    if (lines.length === 0) {
        throw new Error('Innertube returned no transcript data.');
    }

    const text = lines.join('\n');
    const fname = `${videoId}-transcript.txt`;
    fs.writeFileSync(path.join(OUTPUT_DIR, fname), text, 'utf-8');
    emitProgress(`Transcript saved: ${fname} (${text.length} chars, ${lines.length} lines)`);

    return { transcript: text, downloadUrl: `/api/download/${fname}`, filename: fname, method: 'innertube' };
}

// --- Strategy 3: Page scrape for captionTracks ---
async function fetchFromPage(videoId: string, emitProgress: ProgressEmitter): Promise<ToolResult> {
    emitProgress('Fetching YouTube page for caption tracks...');

    const html = await httpGet(`https://www.youtube.com/watch?v=${videoId}`, {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        'Accept-Language': 'en-US,en;q=0.9',
        'Cookie': 'CONSENT=YES+cb.20210328-17-p0.en+FX+999',
    });

    if (!html || html.length < 1000) {
        throw new Error('YouTube returned empty or blocked page.');
    }

    // Try multiple regex patterns for caption tracks
    const patterns = [
        /"captionTracks"\s*:\s*(\[.*?\])/s,
        /captionTracks.*?(\[.*?\])/s,
        /"playerCaptionsTracklistRenderer"\s*:\s*\{.*?"captionTracks"\s*:\s*(\[.*?\])/s,
    ];

    let tracks: any[] | null = null;
    for (const pattern of patterns) {
        const m = html.match(pattern);
        if (m) {
            try {
                tracks = JSON.parse(m[1]);
                break;
            } catch {
                continue;
            }
        }
    }

    if (!tracks || tracks.length === 0) {
        throw new Error('No caption tracks found in page HTML.');
    }

    // Prefer English captions
    const enTrack =
        tracks.find((t: any) => t.languageCode === 'en' && !t.kind) ||
        tracks.find((t: any) => t.languageCode === 'en') ||
        tracks.find((t: any) => t.languageCode?.startsWith('en')) ||
        tracks[0];

    if (!enTrack?.baseUrl) {
        throw new Error('No usable caption track URL.');
    }

    emitProgress(`Found captions: ${enTrack.name?.simpleText || enTrack.languageCode} (${enTrack.kind || 'manual'})`);

    // Fetch the captions XML -- add fmt=json3 for structured data
    let text = '';
    try {
        const json3Url = enTrack.baseUrl + (enTrack.baseUrl.includes('?') ? '&' : '?') + 'fmt=json3';
        const json3Response = await httpGet(json3Url, { 'User-Agent': 'Mozilla/5.0' });
        text = parseJson3Captions(json3Response);
    } catch {
        // fallback to XML
    }

    if (!text) {
        const xmlResponse = await httpGet(enTrack.baseUrl, { 'User-Agent': 'Mozilla/5.0' });
        text = parseXmlCaptions(xmlResponse);
    }

    if (!text.trim()) {
        throw new Error('Caption content is empty after parsing.');
    }

    const fname = `${videoId}-transcript.txt`;
    fs.writeFileSync(path.join(OUTPUT_DIR, fname), text, 'utf-8');
    emitProgress(`Transcript saved: ${fname} (${text.length} chars)`);

    return { transcript: text, downloadUrl: `/api/download/${fname}`, filename: fname, method: 'page-scrape' };
}

// --- HTTP helpers ---
function httpGet(url: string, headers: Record<string, string> = {}): Promise<string> {
    return new Promise((resolve, reject) => {
        const client = url.startsWith('https') ? https : http;
        const parsed = new URL(url);
        const opts = {
            hostname: parsed.hostname,
            port: parsed.port,
            path: parsed.pathname + parsed.search,
            method: 'GET',
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                ...headers,
            },
        };

        const req = client.request(opts, (res) => {
            if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
                return httpGet(res.headers.location, headers).then(resolve).catch(reject);
            }
            let data = '';
            res.on('data', (c: Buffer) => { data += c; });
            res.on('end', () => resolve(data));
            res.on('error', reject);
        });
        req.on('error', reject);
        req.end();
    });
}

function httpPost(url: string, body: string, headers: Record<string, string> = {}): Promise<string> {
    return new Promise((resolve, reject) => {
        const parsed = new URL(url);
        const opts = {
            hostname: parsed.hostname,
            port: parsed.port || 443,
            path: parsed.pathname + parsed.search,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': Buffer.byteLength(body),
                'User-Agent': 'Mozilla/5.0',
                ...headers,
            },
        };

        const req = https.request(opts, (res) => {
            let data = '';
            res.on('data', (c: Buffer) => { data += c; });
            res.on('end', () => resolve(data));
            res.on('error', reject);
        });
        req.on('error', reject);
        req.write(body);
        req.end();
    });
}

// --- Parsers ---
function parseVtt(vtt: string): string {
    const seen = new Set<string>();
    return vtt.split('\n')
        .map((l) => l.trim())
        .filter((l) => l && l !== 'WEBVTT' && !l.includes('-->') && !/^\d+$/.test(l) && !l.startsWith('Kind:') && !l.startsWith('Language:') && !l.startsWith('NOTE'))
        .map((l) => l.replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').trim())
        .filter((l) => { if (l && !seen.has(l)) { seen.add(l); return true; } return false; })
        .join('\n');
}

function parseSrt(srt: string): string {
    const seen = new Set<string>();
    return srt.split('\n')
        .map((l) => l.trim())
        .filter((l) => l && !l.includes('-->') && !/^\d+$/.test(l))
        .map((l) => l.replace(/<[^>]+>/g, '').trim())
        .filter((l) => { if (l && !seen.has(l)) { seen.add(l); return true; } return false; })
        .join('\n');
}

function parseXmlCaptions(xml: string): string {
    const lines: string[] = [];
    const re = /<text[^>]*>([\s\S]*?)<\/text>/g;
    let m: RegExpExecArray | null;
    while ((m = re.exec(xml)) !== null) {
        const t = decodeEntities(m[1]).replace(/<[^>]+>/g, '').trim();
        if (t) lines.push(t);
    }
    return lines.join('\n');
}

function parseJson3Captions(json: string): string {
    try {
        const data = JSON.parse(json);
        const events = data?.events;
        if (!events) return '';

        const lines: string[] = [];
        for (const event of events) {
            if (event.segs) {
                const text = event.segs.map((s: any) => s.utf8 || '').join('').trim();
                if (text && text !== '\n') lines.push(text);
            }
        }
        return lines.join('\n');
    } catch {
        return '';
    }
}

function decodeEntities(str: string): string {
    return str
        .replace(/&amp;/g, '&')
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&quot;/g, '"')
        .replace(/&#39;/g, "'")
        .replace(/&#x27;/g, "'")
        .replace(/&#(\d+);/g, (_, num) => String.fromCharCode(parseInt(num, 10)));
}