import { promisify } from 'node:util';
import { execFile as _execFile } from 'node:child_process';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { existsSync } from 'node:fs';

const execFile = promisify(_execFile);

export type DownloadResult = { bytes: Uint8Array; description: string; filePath?: string };

export async function downloadInstagramVideoBytes(shareUrl: string): Promise<DownloadResult | null> {
  // Prefer project venv Python if present, fall back to env or system python3
  const venvPython = join(process.cwd(), 'tools', 'instaloader', '.venv', 'bin', 'python');
  const pythonBin = existsSync(venvPython) ? venvPython : process.env.PYTHON_BIN || 'python3';
  const scriptPath = join(process.cwd(), 'tools', 'instaloader', 'download_ig.py');
  try {
    const { stdout } = await execFile(pythonBin, [scriptPath, '--url', shareUrl, '--out', join(process.cwd(), 'tools', 'instaloader', 'downloads')], {
      env: {
        ...process.env,
        IG_USERNAME: process.env.IG_USERNAME || '',
        IG_PASSWORD: process.env.IG_PASSWORD || '',
        IG_SESSIONFILE: process.env.IG_SESSIONFILE || '',
      },
      timeout: 120_000,
    });
    const last = stdout.trim().split(/\r?\n/).pop();
    if (!last) return null;
    let videoPath = last;
    let description = '';
    try {
      const parsed = JSON.parse(last);
      videoPath = parsed.video_path || parsed.path || parsed;
      description = parsed.description || '';
    } catch {}
    if (!videoPath) return null;
    const buf = await readFile(videoPath);
    return { bytes: new Uint8Array(buf), description, filePath: videoPath };
  } catch {
    return null;
  }
}


