import { getMnoteRuntimeConfig } from "@/lib/runtime-config";
import { buildForwardHeaders } from "@/lib/server/forward-headers";
import { pickLeptosTiptapRuntimePageOptions } from "@/lib/documents/page-option-semantics";
import type { DocumentAiCapabilityConfig } from "@/lib/ai-agent/document-config";
import type { PageOptionsState } from "@/types/page-options";

type AgentMessage = { role: "user" | "assistant"; content: string };

type RequestPayload = {
  maxSteps?: number;
  messages: AgentMessage[];
  context?: {
    documentId?: string;
    documentBlocks?: unknown;
    pageOptions?: PageOptionsState;
    node?: unknown;
    subtree?: unknown;
    outline?: unknown;
    evidence?: unknown;
  };
  options?: {
    ai?: {
      model?: string;
      modelKey?: string;
      profileId?: string;
      sessionId?: string;
    };
  };
};

function resolveBackendUrl(): string | null {
  const cfg = getMnoteRuntimeConfig();
  const backendUrl =
    process.env.BACKEND_INTERNAL_URL || process.env.BACKEND_URL || cfg.backendUrl;
  return backendUrl?.trim().replace(/\/+$/, "") || null;
}

function buildErrorMessage(payload: unknown, fallback: string): string {
  if (payload && typeof payload === "object" && "detail" in payload) {
    return String((payload as Record<string, unknown>).detail ?? fallback);
  }
  if (payload && typeof payload === "object" && "message" in payload) {
    return String((payload as Record<string, unknown>).message ?? fallback);
  }
  if (payload && typeof payload === "object" && "error" in payload) {
    return String((payload as Record<string, unknown>).error ?? fallback);
  }
  return fallback;
}

export async function startDocumentAiOrchestratorRun(input: {
  request?: Request;
  userId: string;
  payload: RequestPayload;
}): Promise<Response> {
  const backendUrl = resolveBackendUrl();
  if (!backendUrl) {
    throw new Error("未配置 BACKEND_URL");
  }

  const headers = await buildForwardHeaders(input.request);
  headers.set("Content-Type", "application/json");
  const apiKey = (process.env.MNOTE_AI_ORCHESTRATOR_API_KEY || "").trim();
  if (apiKey) {
    headers.set("x-mnote-ai-key", apiKey);
  }

  const response = await fetch(`${backendUrl}/api/v1/ai-agent/document/run`, {
    method: "POST",
    headers,
    body: JSON.stringify({
      userId: input.userId,
      sessionId: String(input.payload.options?.ai?.sessionId ?? "").trim() || null,
      model: String(input.payload.options?.ai?.model ?? "").trim() || null,
      modelKey: String(input.payload.options?.ai?.modelKey ?? "").trim() || null,
      profileId: String(input.payload.options?.ai?.profileId ?? "").trim() || null,
      maxSteps: input.payload.maxSteps,
      messages: input.payload.messages,
      context: {
        documentId: input.payload.context?.documentId ?? null,
        documentBlocks: input.payload.context?.documentBlocks ?? null,
        node: input.payload.context?.node ?? null,
        subtree: input.payload.context?.subtree ?? null,
        outline: input.payload.context?.outline ?? null,
        evidence: input.payload.context?.evidence ?? null,
        pageOptions: input.payload.context?.pageOptions ?? null,
        editorRuntimePageOptions: input.payload.context?.pageOptions
          ? pickLeptosTiptapRuntimePageOptions(input.payload.context.pageOptions)
          : null,
      },
    }),
    cache: "no-store",
  });

  if (!response.ok) {
    const payload = await response.json().catch(() => null);
    throw new Error(buildErrorMessage(payload, `AI orchestrator 请求失败：HTTP ${response.status}`));
  }

  if (!response.body) {
    throw new Error("AI orchestrator 未返回事件流");
  }

  return response;
}

export async function fetchDocumentAiOrchestratorConfig(input?: {
  request?: Request;
}): Promise<DocumentAiCapabilityConfig> {
  const backendUrl = resolveBackendUrl();
  if (!backendUrl) {
    throw new Error("未配置 BACKEND_URL");
  }

  const headers = await buildForwardHeaders(input?.request);
  const apiKey = (process.env.MNOTE_AI_ORCHESTRATOR_API_KEY || "").trim();
  if (apiKey) {
    headers.set("x-mnote-ai-key", apiKey);
  }

  const response = await fetch(`${backendUrl}/api/v1/ai-agent/document/config`, {
    method: "GET",
    headers,
    cache: "no-store",
  });

  if (!response.ok) {
    const payload = await response.json().catch(() => null);
    throw new Error(buildErrorMessage(payload, `AI orchestrator config 请求失败：HTTP ${response.status}`));
  }

  return (await response.json()) as DocumentAiCapabilityConfig;
}
