import { NextResponse } from 'next/server';
import { listAgents, getDefaultAgentId, resolveTerminalLaunch } from '@/lib/agents';
import { loadSettings } from '@/lib/settings';

export async function GET(req: Request) {
  const url = new URL(req.url);
  const resolve = url.searchParams.get('resolve');

  // GET /api/agents?resolve=claude[&scene=help] → resolve launch info for an
  // agent in a given scene (terminal default; help/task/etc. pick models[scene]).
  if (resolve) {
    const scene = url.searchParams.get('scene') as 'terminal' | 'task' | 'telegram' | 'help' | 'mobile' | null;
    const info = resolveTerminalLaunch(resolve, scene || undefined);
    return NextResponse.json(info);
  }

  // ?include=cli|api|all (default: cli) — API profiles aren't useful in
  // Terminal / Task / Pipeline pickers (no CLI binary to spawn), so the
  // default hides them. WorkspaceView's API mode passes ?include=all
  // (or ?include=api) to surface them when needed.
  const include = (url.searchParams.get('include') || 'cli').toLowerCase();
  const cliAgents = listAgents();
  const apiAgents = include === 'cli' ? [] : apiProfilesAsAgents();
  const agents = include === 'cli' ? cliAgents
    : include === 'api' ? apiAgents
    : [...cliAgents, ...apiAgents];
  const defaultAgent = getDefaultAgentId();
  return NextResponse.json({ agents, defaultAgent });
}

// Render settings.apiProfiles as agent-shaped entries so the workspace
// API-mode picker can list them (Phase 2 moved them out of listAgents).
function apiProfilesAsAgents() {
  const profiles = loadSettings().apiProfiles || {};
  return Object.entries(profiles)
    .filter(([, p]: [string, any]) => p && p.enabled !== false)
    .map(([id, p]: [string, any]) => ({
      id,
      name: p.name || id,
      path: '',
      enabled: true,
      type: 'generic' as const,
      capabilities: { supportsResume: false, supportsStreamJson: false, supportsModel: false, supportsSkipPermissions: false, hasSessionFiles: false, requiresTTY: false },
      isProfile: true,
      backendType: 'api' as const,
      provider: p.provider,
      model: p.model,
    }));
}
