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

// The .NET agent backend runs as a separate process on port 8000.
// This runtime proxies CopilotKit requests to it via AG-UI protocol.
const AGENT_URL = process.env.AGENT_URL || "http://localhost:8000";

console.log("[copilotkit/route] Initializing CopilotKit runtime");
console.log(`[copilotkit/route] AGENT_URL: ${AGENT_URL}`);

function createAgent() {
  return new HttpAgent({ url: `${AGENT_URL}/` });
}

// Interrupt-adapted backend — see agent/InterruptAgent.cs. This is a
// SEPARATE .NET agent mounted at /interrupt-adapted so the `gen-ui-interrupt`
// and `interrupt-headless` demos get tool-based approval-mode semantics
// without polluting the sales agent's tool list.
function createInterruptAgent() {
  return new HttpAgent({ url: `${AGENT_URL}/interrupt-adapted` });
}

// Register the same agent under all names used by demo pages.
// The .NET backend exposes a single ProverbsAgent mapped at "/".
const agentNames = [
  "agentic_chat",
  "human_in_the_loop",
  "tool-rendering",
  "gen-ui-tool-based",
  "gen-ui-agent",
  "shared-state-read",
  "shared-state-write",
  "shared-state-streaming",
  "tool-rendering-default-catchall",
  "tool-rendering-custom-catchall",
  "tool-rendering-reasoning-chain",
  // Slot demos that reuse the default SalesAgent backend (mounted at `/` on
  // the .NET side). Differentiation happens entirely on the frontend.
  "prebuilt-sidebar",
  "prebuilt-popup",
  "chat-slots",
  "chat-customization-css",
  "headless-simple",
  "headless-complete",
  // NOTE: `frontend_tools` uses an underscore to match the demo's expected
  // agent name (the demo page passes `agent="frontend_tools"`).
  "frontend_tools",
  "frontend-tools-async",
  "readonly-state-agent-context",
];

// Interrupt-adapted demo agent names — these route to the separate .NET
// InterruptAgent backend instead of the sales agent.
const interruptAgentNames = ["gen-ui-interrupt", "interrupt-headless"];

const agents: Record<string, AbstractAgent> = {};
for (const name of agentNames) {
  agents[name] = createAgent();
}
for (const name of interruptAgentNames) {
  agents[name] = createInterruptAgent();
}
agents["default"] = createAgent();

// hitl-in-app is mounted at a dedicated path on the .NET backend
// (`/hitl-in-app`, see `agent/HitlInAppAgent.cs` + `agent/Program.cs`) so
// it can run with its own support-ops system prompt rather than the sales
// pipeline prompt exposed at `/`. The frontend tool `request_user_approval`
// is registered client-side via `useFrontendTool` and resolves via a modal
// rendered OUTSIDE the chat surface.
agents["hitl-in-app"] = new HttpAgent({ url: `${AGENT_URL}/hitl-in-app` });

// In-chat HITL demo backend. The frontend registers the `book_call` tool
// via `useHumanInTheLoop`; the .NET agent owns no tools. See
// agent/HitlInChatAgent.cs.
agents["hitl-in-chat"] = new HttpAgent({ url: `${AGENT_URL}/hitl-in-chat` });

// Shared State (Read + Write) demo backend. UI owns `preferences` (written
// via agent.setState) and the agent owns `notes` via the `set_notes` tool.
// See agent/SharedStateReadWriteAgent.cs.
agents["shared-state-read-write"] = new HttpAgent({
  url: `${AGENT_URL}/shared-state-read-write`,
});

// Sub-Agents demo backend. Supervisor delegates to research / writing /
// critique sub-agents and emits a delegation snapshot to the UI on each
// tool call. See agent/SubagentsAgent.cs.
agents["subagents"] = new HttpAgent({ url: `${AGENT_URL}/subagents` });

console.log(
  `[copilotkit/route] Registered ${Object.keys(agents).length} agent names: ${Object.keys(agents).join(", ")}`,
);

export const POST = async (req: NextRequest) => {
  const url = req.url;
  const contentType = req.headers.get("content-type");
  console.log(`[copilotkit/route] POST ${url} (content-type: ${contentType})`);

  try {
    const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
      endpoint: "/api/copilotkit",
      serviceAdapter: new ExperimentalEmptyAdapter(),
      runtime: new CopilotRuntime({
        // @ts-ignore -- Published CopilotRuntime agents type wraps Record in MaybePromise<NonEmptyRecord<...>> which rejects plain Records; fixed in source, pending release
        agents,
      }),
    });

    const response = await handleRequest(req);
    console.log(`[copilotkit/route] Response status: ${response.status}`);
    return response;
  } catch (error: unknown) {
    const err = error as Error;
    console.error(`[copilotkit/route] ERROR: ${err.message}`);
    console.error(`[copilotkit/route] Stack: ${err.stack}`);
    return NextResponse.json(
      { error: err.message, stack: err.stack },
      { status: 500 },
    );
  }
};

export const GET = async () => {
  console.log("[copilotkit/route] GET /api/copilotkit (health probe)");

  let agentStatus = "unknown";
  try {
    const res = await fetch(`${AGENT_URL}/health`, {
      signal: AbortSignal.timeout(3000),
    });
    agentStatus = res.ok ? "reachable" : `error (${res.status})`;
  } catch (e: unknown) {
    agentStatus = `unreachable (${(e as Error).message})`;
  }

  return NextResponse.json({
    status: "ok",
    agent_url: AGENT_URL,
    agent_status: agentStatus,
    env: {
      NODE_ENV: process.env.NODE_ENV,
    },
  });
};
