import { u as useFileNodesInSelectedDrive, y as useSelectedDriveId } from "./dist-DAY54QOk.js";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
//#region editors/knowledge-vault/hooks/subgraph-endpoint.ts
/**
* Resolve the URL of the package's `knowledgeGraph` subgraph for the
* current Connect host. Used by `useGraphSearch` and `ActivityView`, both
* of which talk directly to the switchboard via plain fetch (no apollo
* client wrapping).
*
* Priority:
*   1. `VITE_SUBGRAPH_URL` env override (escape hatch for unusual deploys)
*   2. Explicit Connect → Switchboard mappings (`DOMAIN_MAP`)
*   3. Vetra subdomain pattern: connect.<slug>.vetra.io ↔ switchboard.<slug>.vetra.io
*   4. Any localhost / 127.0.0.1 → http://localhost:4001
*      (covers `ph vetra` direct on 3001 AND Cursor/VS Code remote-dev
*      port-forwarding which proxies Connect to a random localhost port
*      like 26045 — the IDE typically auto-forwards 4001 too).
*   5. Same-origin (production where the subgraph is co-hosted)
*/
const SUBGRAPH_PATH = "/graphql/knowledgeGraph";
const DOMAIN_MAP = { "connect-dev.powerhouse.xyz": "https://switchboard-dev.powerhouse.xyz/graphql/knowledgeGraph" };
function resolveKnowledgeGraphEndpoint() {
	const envUrl = typeof import.meta !== "undefined" && import.meta.env?.VITE_SUBGRAPH_URL;
	if (envUrl) return envUrl;
	const hostname = globalThis.window?.location?.hostname;
	if (hostname && DOMAIN_MAP[hostname]) return DOMAIN_MAP[hostname];
	if (hostname && /^connect\..+\.vetra\.io$/.test(hostname)) return `https://${hostname.replace(/^connect\./, "switchboard.")}${SUBGRAPH_PATH}`;
	if (hostname === "localhost" || hostname === "127.0.0.1") return `http://localhost:4001${SUBGRAPH_PATH}`;
	return SUBGRAPH_PATH;
}
//#endregion
//#region editors/knowledge-vault/hooks/use-graph-metadata.ts
/**
* Single-query sidebar metadata source for the Knowledge Vault editor.
*
* Replaces the old per-document fetch loop (`useDocumentsSafe` ×348)
* with one GraphQL call to the `knowledgeGraph` subgraph. The subgraph
* reads from a relational projection (`graph_nodes`, `graph_topics`,
* `graph_edges`) maintained by the in-process `GraphIndexerProcessor`.
*
* Why this is fast:
* - One round-trip instead of N (348+ for our vault).
* - Returns only the metadata the sidebar/list views actually need —
*   not the full document state with operation history.
* - The processor pre-denormalizes joins (topics already joined per
*   node), so no client-side stitching.
*
* Why this is resilient:
* - The hook returns `{ nodes, edges, isLoading, error, refetch }`.
*   Callers render an error state instead of crashing if the subgraph
*   is unreachable, and can offer a manual retry.
* - On first open of a drive, the processor's historical replay may
*   not yet be done. The hook auto-refetches when the drive's file
*   node count changes (a new doc landed → likely time to refresh).
*   Initial empty state is shown gracefully; it fills in as the
*   processor catches up.
*
* The full per-document state is still fetched lazily when the user
* opens a single note (via `useDocumentByIdSafe`).
*/
const NODES_QUERY = `
  query GraphNodes($driveId: ID!) {
    knowledgeGraphNodes(driveId: $driveId) {
      documentId
      title
      description
      noteType
      status
      topics
      author
      sourceOrigin
      createdAt
      updatedAt
    }
    knowledgeGraphEdges(driveId: $driveId) {
      id
      sourceDocumentId
      targetDocumentId
      linkType
      targetTitle
    }
  }
`;
const DRIVE_TREE_QUERY = `
  query DriveTree($id: String!) {
    document(identifier: $id) {
      document { state }
    }
  }
`;
const EMPTY_NODES = [];
const EMPTY_EDGES = [];
function reactorEndpoint() {
	const hostname = globalThis.window?.location?.hostname;
	if (hostname === "localhost" || hostname === "127.0.0.1") return "http://localhost:4001/graphql";
	if (hostname && /^connect\..+\.vetra\.io$/.test(hostname)) return `https://${hostname.replace(/^connect\./, "switchboard.")}/graphql`;
	return "/graphql";
}
async function fetchDriveAllNodes(driveId) {
	const res = await fetch(reactorEndpoint(), {
		method: "POST",
		headers: { "Content-Type": "application/json" },
		body: JSON.stringify({
			query: DRIVE_TREE_QUERY,
			variables: { id: driveId }
		})
	});
	if (!res.ok) return [];
	const json = await res.json();
	if (json.errors?.length) return [];
	return (json.data?.document?.document?.state?.global?.nodes ?? []).filter((n) => typeof n === "object" && n !== null && (n.kind === "file" || n.kind === "folder")).map((n) => ({
		id: n.id,
		name: n.name,
		kind: n.kind,
		documentType: n.documentType ?? void 0,
		parentFolder: n.parentFolder ?? null
	}));
}
function useGraphMetadata() {
	const driveId = useSelectedDriveId();
	const fileNodes = useFileNodesInSelectedDrive();
	const [nodes, setNodes] = useState(EMPTY_NODES);
	const [edges, setEdges] = useState(EMPTY_EDGES);
	const [allNodes, setAllNodes] = useState([]);
	const serverFileNodes = useMemo(() => allNodes.filter((n) => n.kind === "file" && !!n.documentType).map((n) => ({
		id: n.id,
		name: n.name,
		documentType: n.documentType,
		parentFolder: n.parentFolder
	})), [allNodes]);
	const [isLoading, setIsLoading] = useState(false);
	const [error, setError] = useState(null);
	const [refetchKey, setRefetchKey] = useState(0);
	useRef("");
	const driveFingerprint = useMemo(() => `${driveId ?? ""}:${refetchKey}`, [driveId, refetchKey]);
	const fileCount = fileNodes?.length ?? 0;
	const lastSeenCountRef = useRef(-1);
	useEffect(() => {
		if (fileCount === lastSeenCountRef.current) return;
		const prev = lastSeenCountRef.current;
		lastSeenCountRef.current = fileCount;
		if (prev === -1) return;
		const timer = setTimeout(() => setRefetchKey((k) => k + 1), 1500);
		return () => clearTimeout(timer);
	}, [fileCount]);
	useEffect(() => {
		if (!driveId) {
			setNodes(EMPTY_NODES);
			setEdges(EMPTY_EDGES);
			setError(null);
			return;
		}
		let cancelled = false;
		setIsLoading(true);
		setError(null);
		const endpoint = resolveKnowledgeGraphEndpoint();
		fetch(endpoint, {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({
				query: NODES_QUERY,
				variables: { driveId }
			})
		}).then(async (res) => {
			if (!res.ok) throw new Error(`HTTP ${res.status} from ${endpoint}`);
			const json = await res.json();
			if (json.errors?.length) throw new Error(json.errors.map((e) => e.message ?? "?").join("; "));
			return json.data;
		}).then((data) => {
			if (cancelled) return;
			setNodes(data?.knowledgeGraphNodes ?? EMPTY_NODES);
			setEdges(data?.knowledgeGraphEdges ?? EMPTY_EDGES);
		}).then(() => fetchDriveAllNodes(driveId).then((nodes) => {
			if (cancelled) return;
			setAllNodes(nodes);
		})).catch((err) => {
			if (cancelled) return;
			const e = err instanceof Error ? err : new Error(String(err));
			console.warn("[useGraphMetadata] fetch failed:", e.message);
			setError(e);
		}).finally(() => {
			if (!cancelled) setIsLoading(false);
		});
		return () => {
			cancelled = true;
		};
	}, [driveId, driveFingerprint]);
	return {
		nodes,
		edges,
		nodeMap: useMemo(() => {
			const m = /* @__PURE__ */ new Map();
			for (const n of nodes) m.set(n.documentId, n);
			return m;
		}, [nodes]),
		fileNodes: serverFileNodes,
		allNodes,
		isLoading,
		error,
		refetch: useCallback(() => {
			setRefetchKey((k) => k + 1);
		}, [])
	};
}
//#endregion
export { resolveKnowledgeGraphEndpoint as n, useGraphMetadata as t };

//# sourceMappingURL=use-graph-metadata-C0FHs2qM.js.map