import { headers } from "next/headers";
import { getAuthedConvexClient } from "@/lib/convex/route";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { buildDocumentBridgeContext, buildDocumentQueryEnvelope } from "@/lib/documents/bridge";
import { executeRustBridgeQueryTransport, resolveRustBridgeQueryPlan } from "@/lib/documents/rust-runtime";
import {
  buildMindmapProjection,
  defaultMindmapData,
  type MindmapProjection,
  type MindmapSimpleMindMapScene,
} from "@/lib/mindmap/mindmap-projection";
import MindmapPageClient from "./mindmap-page-client";

export const MINDMAP_PAGE_LEGACY_COMPAT_CONTRACT = {
  shellOwner: "mnote-web",
  runtimeRole: "simple_mind_map_adapter",
  island: "leptos_mindmap_adapter",
  projectionQueryName: "mindmap.simple_mind_map_scene.get",
  commandName: "mindmap.command.apply",
} as const;

async function fetchMindmapAdapterProjectionOnServer(input: {
  docId: string;
  mindmapId: string;
}): Promise<MindmapSimpleMindMapScene | null> {
  if (!isConvexEnabled()) {
    return {
      schema: "mnote.mindmap.simple_mind_map_scene.v1",
      runtime: "simple-mind-map",
      documentId: input.docId,
      mindmapId: input.mindmapId,
      rootNodeId: null,
      root: defaultMindmapData,
      layout: "logicalStructure",
      theme: "classic",
      themeConfig: {},
      view: {},
      config: {},
      compatPayload: { source: "compat-blob", mindmapId: input.mindmapId },
      kernelRevision: 1,
      source: "compat-blob",
      owner: "rust-kernel",
      meta: null,
    };
  }

  try {
    const headerList = await headers();
    const requestHeaders = new Headers();
    [
      "cookie",
      "authorization",
      "x-request-id",
      "x-trace-id",
      "x-session-id",
      "x-source-channel",
      "x-source-client",
      "user-agent",
    ].forEach((name) => {
      const value = headerList.get(name);
      if (value) {
        requestHeaders.set(name, value);
      }
    });

    const request = new Request("http://mnote.local/mindmap/projection", {
      method: "GET",
      headers: requestHeaders,
    });
    const { client } = await getAuthedConvexClient();
    const context = await buildDocumentBridgeContext({
      request,
      workspaceId: null,
    });
    const envelope = buildDocumentQueryEnvelope({
      name: MINDMAP_PAGE_LEGACY_COMPAT_CONTRACT.projectionQueryName,
      payload: {
        documentId: input.docId,
        mindmapId: input.mindmapId,
        workspaceId: null,
      },
    });
    const plan = await resolveRustBridgeQueryPlan({
      context,
      envelope,
    });
    const result = await executeRustBridgeQueryTransport<MindmapSimpleMindMapScene | null>({
      client,
      plan,
    });

    return result
      ? {
          ...result,
          source: result.source ?? "compat-blob",
          owner: result.owner ?? "rust-kernel",
          meta: result.meta ?? {
            requestId: context.requestId,
            traceId: context.traceId,
            workspaceId: context.workspaceId,
            documentId: input.docId,
            pageId: input.docId,
            mindmapId: input.mindmapId,
            attachmentId: input.mindmapId,
          },
        }
      : null;
  } catch {
    return null;
  }
}

function buildStandaloneProjectionFromAdapter(input: {
  docId: string;
  mindmapId: string;
  adapterProjection: MindmapSimpleMindMapScene | null;
}): MindmapProjection | null {
  if (!input.adapterProjection) return null;
  return buildMindmapProjection({
    documentId: input.docId,
    mindmapId: input.mindmapId,
    data: input.adapterProjection.root ?? defaultMindmapData,
    source: input.adapterProjection.source ?? "compat-blob",
    owner: input.adapterProjection.owner ?? "rust-kernel",
    meta: input.adapterProjection.meta,
  });
}

export default async function MindmapFullscreenPage({
  params,
}: {
  params: Promise<{ docId: string; mindmapId: string }>;
}) {
  const { docId, mindmapId } = await params;
  const initialAdapterProjection = await fetchMindmapAdapterProjectionOnServer({ docId, mindmapId });
  const initialProjection = buildStandaloneProjectionFromAdapter({
    docId,
    mindmapId,
    adapterProjection: initialAdapterProjection,
  });

  return (
    <main
      data-leptos-mindmap-island={MINDMAP_PAGE_LEGACY_COMPAT_CONTRACT.island}
      data-runtime-role={MINDMAP_PAGE_LEGACY_COMPAT_CONTRACT.runtimeRole}
      data-shell-owner={MINDMAP_PAGE_LEGACY_COMPAT_CONTRACT.shellOwner}
      data-projection-query={MINDMAP_PAGE_LEGACY_COMPAT_CONTRACT.projectionQueryName}
      data-command-name={MINDMAP_PAGE_LEGACY_COMPAT_CONTRACT.commandName}
      data-adapter-source={initialAdapterProjection?.source ?? "compat-blob"}
      data-kernel-revision={initialAdapterProjection?.kernelRevision ?? 1}
    >
      <MindmapPageClient
        docId={docId}
        mindmapId={mindmapId}
        initialProjection={initialProjection}
      />
    </main>
  );
}
