import type { ConvexHttpClient } from "convex/browser";
import type { SidebarDatasetListQueryResult } from "@/lib/sidebar-data";
import type { KernelFileTreeProjection } from "@/lib/kernel-file-tree";
import {
  buildDocumentBridgeContextWithActor,
  buildDocumentQueryEnvelope,
  type BridgeActor,
} from "@/lib/documents/bridge";
import { executeRustBridgeQuery } from "@/lib/documents/rust-runtime";

export async function resolveKernelFileTreeProjection(input: {
  client: ConvexHttpClient;
  request: Request;
  workspaceId: string;
  actor: BridgeActor;
  dataset: SidebarDatasetListQueryResult;
  rootNodeId?: string | null;
  depth?: number | null;
}): Promise<KernelFileTreeProjection> {
  const context = buildDocumentBridgeContextWithActor({
    request: input.request,
    actor: input.actor,
    workspaceId: input.workspaceId,
  });

  return executeRustBridgeQuery<KernelFileTreeProjection>({
    context,
    envelope: buildDocumentQueryEnvelope({
      name: "kernel.project_view",
      payload: {
        projection: "file_tree",
        workspaceId: input.workspaceId,
        rootNodeId: input.rootNodeId ?? null,
        depth: input.depth ?? null,
        includeEdges: true,
        includeContent: false,
        nodeTypes: ["page"],
      },
    }),
    data: input.dataset as unknown as Record<string, unknown>,
  });
}

export function attachKernelFileTreeProjection<T extends SidebarDatasetListQueryResult>(input: {
  dataset: T;
  projection: KernelFileTreeProjection;
}): T {
  return {
    ...input.dataset,
    kernel_file_tree_projection: input.projection,
  };
}
