/**
 * Makima Cloudflare Agent — Worker Entry Point
 *
 * Routes incoming requests to the MakimaAgent Durable Object which manages
 * the upstream WebSocket connection to the Makima server and relays tasks
 * to downstream native daemon instances.
 *
 * Routes:
 *   GET  /                → Agent status (JSON)
 *   GET  /status          → Agent status (JSON)
 *   GET  /health          → Health check
 *   GET  /tasks           → Task history (paginated)
 *   GET  /logs            → Connection logs
 *   POST /reconnect       → Force upstream reconnection
 *   *    /ws              → WebSocket upgrade for downstream daemons
 *   *    /agent/*         → Forwarded to Agent's onRequest handler
 */

import { MakimaAgent } from "./agent";
import type { Env } from "./types";

export { MakimaAgent };

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    const url = new URL(request.url);

    // Use a singleton Durable Object — all traffic routes to one agent
    // instance identified by a fixed name. This ensures a single persistent
    // upstream WebSocket to the Makima server.
    const agentId = env.MAKIMA_AGENT.idFromName("makima-relay-primary");
    const agent = env.MAKIMA_AGENT.get(agentId);

    // WebSocket upgrade path — downstream daemons connect here
    if (url.pathname === "/ws" || url.pathname === "/ws/daemon") {
      const upgradeHeader = request.headers.get("Upgrade");
      if (upgradeHeader !== "websocket") {
        return new Response("Expected WebSocket upgrade", { status: 426 });
      }
      // Forward the WebSocket upgrade to the Durable Object
      return agent.fetch(request);
    }

    // All other routes are forwarded to the Durable Object's onRequest handler
    return agent.fetch(request);
  },
};
