import { createRouter } from '../../create-router';
import { listAgents, getAgentByDirName } from './agent-files';
import { startAgentRun, listAgentRuns } from './agent-runner';
import { readCategoryOrder } from '../tasks/task-files';

type TriggerConfig = { type: 'file'; extensions: string[] } | { type: 'directory' };

export const agentsRouter = createRouter();

agentsRouter.get('/', async (ctx) => {
  const summaries = await listAgents();
  return ctx.json(
    summaries.map((row) => ({
      dirName: row.dirName,
      name: row.name,
      description: row.description,
      category: row.category,
      triggers: (row.trigger as TriggerConfig[]) ?? [],
    })),
  );
});

// Declared before '/:name', which would otherwise match "categories" and "runs".
agentsRouter.get('/categories', async (ctx) => ctx.json(await readCategoryOrder()));

agentsRouter.get('/runs', (ctx) => ctx.json(listAgentRuns(ctx.req.query('agent') || undefined)));

agentsRouter.get('/:name', async (ctx) => {
  const agent = await getAgentByDirName(ctx.req.param('name'));
  if (!agent) return ctx.text('Not found', 404);

  return ctx.json({
    dirName: agent.dirName,
    name: agent.name,
    description: agent.description,
    category: agent.category,
    version: agent.version,
    model: agent.model,
    inputs: agent.inputs,
    trigger: agent.trigger,
    tags: agent.tags,
    concurrency: agent.concurrency,
    timeout: agent.timeout,
    body: agent.body,
    filePath: agent.filePath,
  });
});

// POST /agents/:name/run — open the run's session and return immediately. The run itself is watched
// through /chat; there is no job row and nothing to poll here.
agentsRouter.post('/:name/run', async (ctx) => {
  const user = ctx.get('user');
  const body = await ctx.req.json<{ inputs?: Record<string, unknown> }>().catch(() => ({}) as { inputs?: undefined });

  try {
    const result = await startAgentRun({
      dirName: ctx.req.param('name'),
      inputs: body.inputs ?? {},
      user: { id: user.id, email: user.email, username: user.username ?? '' },
    });
    return ctx.json(result);
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Failed to start agent run';
    return ctx.text(message, message === 'Agent not found' ? 404 : 400);
  }
});
