import { createContext as e, useCallback as t, useContext as n, useMemo as r, useState as i } from "react";
import { jsx as a } from "react/jsx-runtime";
import { useQuery as o, useQueryClient as s } from "@tanstack/react-query";
//#region src/features/workbench/providers/RemoteFileExplorerProvider.tsx
function c() {
	return "http://localhost:8000";
}
async function l() {
	return (await fetch(`${c()}/api/v1/auth/refresh`, {
		method: "POST",
		credentials: "include"
	})).ok;
}
async function u(e, t) {
	let n = await fetch(e, t);
	return (n.status === 401 || n.status === 403) && await l() ? fetch(e, t) : n;
}
var d = e(null);
function f({ children: e }) {
	let n = s(), [l, f] = i(/* @__PURE__ */ new Set()), [p, m] = i([]), [h, g] = i(null), _ = o({
		queryKey: ["remote-agent-file-tree"],
		queryFn: async () => {
			let e = await u(`${c()}/api/v1/files/tree?path=./src`, { credentials: "include" });
			if (!e.ok) {
				let t = await e.text();
				throw Error(`Failed to load file tree (${e.status}): ${t}`);
			}
			return await e.json();
		},
		staleTime: 3e4,
		retry: !1
	}), v = o({
		queryKey: ["remote-agent-file-content", h?.path],
		queryFn: async () => {
			let e = c(), t = new URL(`${e}/api/v1/files/read`);
			t.searchParams.set("path", h.path);
			let n = await u(t.toString(), { credentials: "include" });
			if (!n.ok) {
				let e = await n.text();
				throw Error(`Failed to read file (${n.status}): ${e}`);
			}
			return (await n.json()).content;
		},
		enabled: !!h && h.type === "file",
		staleTime: 15e3,
		retry: !1
	}), y = t((e) => {
		f((t) => {
			let n = new Set(t);
			return n.has(e) ? n.delete(e) : n.add(e), n;
		});
	}, []), b = t((e) => {
		e.type === "file" && (g(e), m((t) => t.some((t) => t.path === e.path) ? t : [...t, e]));
	}, []), x = t((e) => {
		m((t) => {
			let n = t.filter((t) => t.path !== e.path);
			if (h?.path === e.path) if (n.length > 0) {
				let r = t.findIndex((t) => t.path === e.path);
				g(n[Math.max(0, r - 1)]);
			} else g(null);
			return n;
		});
	}, [h]), S = t(() => {
		h && m((e) => {
			let t = e.filter((e) => e.path !== h.path);
			if (t.length > 0) {
				let n = e.findIndex((e) => e.path === h.path);
				g(t[Math.max(0, n - 1)]);
			} else g(null);
			return t;
		});
	}, [h]), C = t(() => {
		m([]), g(null);
	}, []), w = t((e) => {
		m([e]), g(e);
	}, []), T = t((e) => {
		m((t) => {
			let n = t.findIndex((t) => t.path === e.path);
			if (n <= 0) return t;
			let r = t.slice(n);
			return h && t.findIndex((e) => e.path === h.path) < n && g(e), r;
		});
	}, [h]), E = t((e) => {
		m((t) => {
			let n = t.findIndex((t) => t.path === e.path);
			if (n < 0 || n >= t.length - 1) return t;
			let r = t.slice(0, n + 1);
			return h && t.findIndex((e) => e.path === h.path) > n && g(e), r;
		});
	}, [h]), D = t(() => {
		n.invalidateQueries({ queryKey: ["remote-agent-file-tree"] });
	}, [n]), O = r(() => ({
		nodes: _.data ?? [],
		isTreeLoading: _.isLoading && !_.data,
		treeError: _.error,
		openFiles: p,
		selectedFile: h,
		fileContent: v.data ?? null,
		isContentLoading: v.isLoading && !!h,
		expandedFolders: l,
		toggleFolder: y,
		selectFile: b,
		closeFile: x,
		closeAll: C,
		closeOthers: w,
		closeToLeft: T,
		closeToRight: E,
		clearSelection: S,
		refreshTree: D,
		isFetchingTree: _.isFetching
	}), [
		_.data,
		_.isLoading,
		_.error,
		_.isFetching,
		p,
		h,
		v.data,
		v.isLoading,
		l,
		y,
		b,
		x,
		C,
		w,
		T,
		E,
		S,
		D
	]);
	return /* @__PURE__ */ a(d.Provider, {
		value: O,
		children: e
	});
}
function p() {
	let e = n(d);
	if (!e) throw Error("useRemoteFileExplorer must be used within RemoteFileExplorerProvider");
	return e;
}
function m() {
	return n(d);
}
//#endregion
export { f as RemoteFileExplorerProvider, m as useOptionalRemoteFileExplorer, p as useRemoteFileExplorer };
