import type { Bindings } from '../types';
import { graphSchema } from '../lib/schemas';
import { parseTriplets } from './triplet-parser';
import { searchNodes } from './search-nodes';
import { buildExecutionGraph } from './graph-builder';

export async function resolveWebhookGraph(
  body: Record<string, unknown>,
  description: string,
  env: Bindings,
): Promise<{ resolvedGraph: Record<string, unknown>; error?: string }> {
  // 路徑 A：triplets 格式
  if (Array.isArray(body.triplets) && body.triplets.length > 0) {
    const parsed = parseTriplets(body.triplets as unknown[]);
    if (!parsed) return { resolvedGraph: {}, error: '無法解析 triplets' };

    const { nodeResults } = await searchNodes(parsed);

    const graphId = `webhook-${Date.now()}`;
    const graphName = description || `Webhook ${new Date().toISOString()}`;
    const graph = buildExecutionGraph(parsed, nodeResults, graphId, graphName) as Record<string, unknown>;

    const parseResult = graphSchema.safeParse(graph);
    if (!parseResult.success) {
      return { resolvedGraph: {}, error: '圖定義產生失敗' };
    }

    return { resolvedGraph: graph };
  }

  // 路徑 B：graph 格式
  if (body.graph && typeof body.graph === 'object') {
    const graphWithDefaults = {
      id: `webhook-${Date.now()}`,
      name: description || `Webhook ${new Date().toISOString()}`,
      ...(body.graph as Record<string, unknown>),
    };
    const parsed = graphSchema.safeParse(graphWithDefaults);
    if (!parsed.success) {
      return { resolvedGraph: {}, error: '圖定義驗證失敗' };
    }
    return { resolvedGraph: graphWithDefaults };
  }

  // 路徑 C：body 直接就是 graph
  if (body.nodes && body.edges) {
    const graphWithDefaults = {
      id: `webhook-${Date.now()}`,
      name: description || `Webhook ${new Date().toISOString()}`,
      ...body,
    };
    const parsed = graphSchema.safeParse(graphWithDefaults);
    if (!parsed.success) {
      return { resolvedGraph: {}, error: '圖定義驗證失敗' };
    }
    return { resolvedGraph: graphWithDefaults };
  }

  return { resolvedGraph: {}, error: '需提供 graph 物件或 triplets 陣列' };
}
