import { NextResponse } from 'next/server';
import { exec } from 'child_process';
import { promisify } from 'util';
import { readdir, stat } from 'fs/promises';
import { join } from 'path';
import { homedir } from 'os';

const execAsync = promisify(exec);

const IS_MAC = process.platform === 'darwin';

async function getWhisperBinaries(): Promise<string[]> {
  try {
    if (IS_MAC) {
      const { stdout } = await execAsync('ls /opt/homebrew/bin/whisper-* 2>/dev/null');
      const bins = stdout
        .trim()
        .split('\n')
        .filter(Boolean)
        .map(p => p.split('/').pop() || p);
      return Array.from(new Set(bins));
    }
    // Linux / WSL2 — check common locations
    const { stdout } = await execAsync(
      'ls /usr/local/bin/whisper-* /usr/bin/whisper-* 2>/dev/null || which whisper-cli 2>/dev/null'
    );
    const bins = stdout
      .trim()
      .split('\n')
      .filter(Boolean)
      .map(p => p.split('/').pop() || p);
    return Array.from(new Set(bins));
  } catch {
    return [];
  }
}

const WHISPER_MODEL_DIRS = (process.env.WHISPER_MODELS_DIR || '')
  .split(':')
  .filter(Boolean)
  .concat([
    join(homedir(), 'whisper-models'),
    ...(IS_MAC
      ? ['/opt/homebrew/share/whisper-cpp/models']
      : ['/usr/local/share/whisper-cpp/models', '/usr/share/whisper-cpp/models']),
    join(homedir(), '.cache', 'whisper'),
  ]);

async function getWhisperModels(): Promise<{
  models: Array<{ name: string; size: number; path: string }>;
  modelsDir: string;
}> {
  for (const dir of WHISPER_MODEL_DIRS) {
    try {
      const files = await readdir(dir);
      const binFiles = files.filter(f => f.endsWith('.bin'));
      if (binFiles.length === 0) continue;
      const models = await Promise.all(
        binFiles.map(async f => {
          const filePath = join(dir, f);
          const s = await stat(filePath);
          return { name: f.replace('ggml-', '').replace('.bin', ''), size: s.size, path: filePath };
        })
      );
      return { models, modelsDir: dir };
    } catch {
      // dir doesn't exist, try next
    }
  }
  return { models: [], modelsDir: WHISPER_MODEL_DIRS[0] };
}

async function getWhisperVersion(): Promise<string> {
  try {
    const { stdout } = await execAsync('whisper-cli -h 2>&1 | head -1');
    const line = stdout.trim();
    return line || 'installed';
  } catch {
    return 'unknown';
  }
}

export async function GET() {
  const [binaries, whisperResult, version] = await Promise.all([
    getWhisperBinaries(),
    getWhisperModels(),
    getWhisperVersion(),
  ]);

  return NextResponse.json({
    installed: binaries.length > 0,
    version,
    binaries,
    models: whisperResult.models,
    modelsDir: whisperResult.modelsDir,
  });
}
