import { getAgent, appendAudit } from '@/lib/runtime.js';
import { readAgentSkills, writeAgentSkills } from '@/lib/agent-skills.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function GET(_req, { params }) {
  const { id } = await params;
  const agent = getAgent(id);
  if (!agent) return Response.json({ ok: false, error: 'agent not found' }, { status: 404 });
  return Response.json({ ok: true, agent_id: id, content: readAgentSkills(id) });
}

export async function PUT(req, { params }) {
  const { id } = await params;
  const agent = getAgent(id);
  if (!agent) return Response.json({ ok: false, error: 'agent not found' }, { status: 404 });

  let body;
  try { body = await req.json(); } catch { return Response.json({ ok: false, error: 'Invalid JSON' }, { status: 400 }); }
  const content = writeAgentSkills(id, body.content);
  appendAudit({
    type: 'agent.skills.update',
    summary: `Updated skills for ${agent.name}`,
    status: 'complete',
    meta: { agent_id: id, bytes: Buffer.byteLength(content) },
  });
  return Response.json({ ok: true, agent_id: id, content });
}
