/**
 * Ligbox Onboard Agents — entry (Fase B/C/D edge)
 * Spec 037 · Roger
 */
import { OnboardMaestro, ProjMailAgent, CfZoneAgent, CfHandoffAgent } from "./onboard-maestro";

export { OnboardMaestro, ProjMailAgent, CfZoneAgent, CfHandoffAgent };

export interface Env {
  VM112_API_BASE: string;
  ONBOARD_MAESTRO: DurableObjectNamespace;
}

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

    if (url.pathname === "/health") {
      return Response.json({
        service: "ligbox-onboard-agents",
        phases: ["A-vm112", "B-maestro", "C-multi-agent", "D-handoff"],
        status: "ok",
      });
    }

    // WebSocket upgrade — Fase B
    if (url.pathname === "/ws/session" && request.headers.get("Upgrade") === "websocket") {
      const sessionId = url.searchParams.get("session") || crypto.randomUUID();
      const domain = url.searchParams.get("domain") || "";
      const id = env.ONBOARD_MAESTRO.idFromName(sessionId);
      const stub = env.ONBOARD_MAESTRO.get(id);
      await stub.fetch(new Request("http://do/init", {
        method: "POST",
        body: JSON.stringify({ sessionId, domain }),
      }));
      // Passthrough: client polls REST until full WS agent chat wired
      return Response.json({
        ok: true,
        sessionId,
        poll: `/api/session/${sessionId}/state`,
        message: "WebSocket scaffold — use REST /api/session for Fase B",
      });
    }

    // REST API
    const m = url.pathname.match(/^\/api\/session\/([^/]+)(\/.*)?$/);
    if (!m) {
      return Response.json({ error: "not found" }, { status: 404 });
    }
    const sessionId = m[1];
    const sub = m[2] || "/state";
    const id = env.ONBOARD_MAESTRO.idFromName(sessionId);
    const stub = env.ONBOARD_MAESTRO.get(id);
    return stub.fetch(new Request(`http://do${sub}`, {
      method: request.method,
      body: request.method !== "GET" ? await request.text() : undefined,
      headers: request.headers,
    }));
  },
};
