// Dedicated runtime for the Shared State Streaming demo.
//
// Routes to the Spring `/shared-state-streaming/run` endpoint, which streams
// tool-call arguments for write_document and emits STATE_SNAPSHOT events with
// the growing document text so the frontend sees per-token updates.

import { NextRequest, NextResponse } from "next/server";
import {
  CopilotRuntime,
  ExperimentalEmptyAdapter,
  copilotRuntimeNextJSAppRouterEndpoint,
} from "@copilotkit/runtime";
import { AbstractAgent, HttpAgent } from "@ag-ui/client";

const AGENT_URL = process.env.AGENT_URL || "http://localhost:8000";

function createAgent(): AbstractAgent {
  return new HttpAgent({ url: `${AGENT_URL}/shared-state-streaming/run` });
}

const sharedStateStreamingAgent = createAgent();
const agents: Record<string, AbstractAgent> = {
  "shared-state-streaming": sharedStateStreamingAgent,
  default: sharedStateStreamingAgent,
};

const runtime = new CopilotRuntime({
  // @ts-ignore -- see main route.ts
  agents,
});

export const POST = async (req: NextRequest) => {
  try {
    const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
      endpoint: "/api/copilotkit-shared-state-streaming",
      serviceAdapter: new ExperimentalEmptyAdapter(),
      runtime,
    });
    return await handleRequest(req);
  } catch (error: unknown) {
    const e = error as { message?: string; stack?: string };
    return NextResponse.json(
      { error: e.message, stack: e.stack },
      { status: 500 },
    );
  }
};
