import {
  getRoleDescription,
  setRoleDescription,
  getCustomInstructions,
  setCustomInstructions,
  CORE_CONTRACTS,
  DEFAULT_ROLE_DESCRIPTION,
  getDesignStyle,
  setDesignStyle,
  DESIGN_STYLES,
  getModel,
  setModel,
  getModels,
} from '@/lib/agent-config.js';
import { CORE_TOOLS } from '@/lib/orchestrator-tools.js';
import { getToolMarketplace, setToolEnabled } from '@/lib/tools/registry.js';

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

export async function GET() {
  const marketplace = getToolMarketplace(CORE_TOOLS);
  // `instructions` exposes only the editable role text (back-compat alias for
  // existing dashboard config modal). Core safety / format contracts are
  // immutable in source and always appended at consumption — surfaced here
  // read-only so the UI can show what's locked.
  return Response.json({
    instructions: getRoleDescription(),
    roleDescription: getRoleDescription(),
    customInstructions: getCustomInstructions(),
    coreContracts: CORE_CONTRACTS,
    defaultRoleDescription: DEFAULT_ROLE_DESCRIPTION,
    designStyle: getDesignStyle(),
    model: getModel(),
    tools: marketplace.marketplace,
    coreTools: marketplace.core,
    connectors: marketplace.connectors,
  });
}

export async function PUT(req) {
  let body;
  try {
    body = await req.json();
  } catch {
    return new Response('Invalid JSON', { status: 400 });
  }
  if (body.instructions !== undefined) {
    if (typeof body.instructions !== 'string') {
      return new Response('instructions must be a string', { status: 400 });
    }
    const trimmed = body.instructions.trim();
    // Hard guard: an empty role would erase the agent's identity. Keep the
    // previously stored role so an accidental clear from any client never
    // wipes the persona. Core contracts are in source and unaffected.
    if (trimmed) setRoleDescription(trimmed);
  }
  if (body.customInstructions !== undefined) {
    if (typeof body.customInstructions !== 'string') {
      return new Response('customInstructions must be a string', { status: 400 });
    }
    setCustomInstructions(body.customInstructions);
  }
  if (body.designStyle !== undefined) {
    if (!DESIGN_STYLES.includes(body.designStyle)) {
      return new Response(`designStyle must be one of: ${DESIGN_STYLES.join(', ')}`, { status: 400 });
    }
    setDesignStyle(body.designStyle);
  }
  if (body.model !== undefined) {
    const allModels = await getModels();
    if (!allModels.find(m => m.id === body.model)) {
      return new Response(`unknown model: ${body.model}`, { status: 400 });
    }
    setModel(body.model);
  }
  if (body.tools !== undefined) {
    if (!Array.isArray(body.tools)) {
      return new Response('tools must be an array', { status: 400 });
    }
    for (const update of body.tools) {
      if (!update || typeof update.name !== 'string' || typeof update.enabled !== 'boolean') {
        return new Response('tool updates must include name and enabled', { status: 400 });
      }
      setToolEnabled(update.name, update.enabled);
    }
  }
  return Response.json({ ok: true });
}
