import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";
//#region src/tui/tui-scoped-models.ts
const STORE_PATH = join(homedir(), ".xopc", "tui-scoped-models.json");
function normalizeWorkspaceKey(cwd) {
	return cwd.replace(/\\/g, "/").replace(/\/+$/, "") || "/";
}
function readStore() {
	try {
		if (!existsSync(STORE_PATH)) return {};
		const raw = readFileSync(STORE_PATH, "utf8");
		const parsed = JSON.parse(raw);
		return parsed && typeof parsed === "object" ? parsed : {};
	} catch {
		return {};
	}
}
function writeStore(data) {
	const dir = join(homedir(), ".xopc");
	if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
	writeFileSync(STORE_PATH, `${JSON.stringify(data, null, 2)}\n`, "utf8");
}
/** Load scoped model refs for Ctrl+P cycling (`null` = all models). */
function loadScopedModelRefs(cwd = process.cwd()) {
	const key = normalizeWorkspaceKey(cwd);
	const entry = readStore().byWorkspace?.[key];
	if (entry === void 0) return null;
	if (entry === null) return null;
	return [...entry];
}
/** Persist scoped model refs for this workspace. Pass `null` to enable all models. */
function saveScopedModelRefs(refs, cwd = process.cwd()) {
	const key = normalizeWorkspaceKey(cwd);
	const byWorkspace = { ...readStore().byWorkspace };
	if (refs === null) byWorkspace[key] = null;
	else byWorkspace[key] = [...refs];
	writeStore({ byWorkspace });
}
function modelRef(choice) {
	return `${choice.provider}/${choice.id}`;
}
/** Filter catalog by scoped refs; empty scoped array falls back to full catalog. */
function filterModelsForCycle(catalog, scopedRefs) {
	if (scopedRefs === null) return catalog;
	if (scopedRefs.length === 0) return catalog;
	const order = new Map(scopedRefs.map((ref, idx) => [ref, idx]));
	return catalog.filter((m) => order.has(modelRef(m))).toSorted((a, b) => (order.get(modelRef(a)) ?? 0) - (order.get(modelRef(b)) ?? 0));
}
//#endregion
export { filterModelsForCycle, loadScopedModelRefs, modelRef, saveScopedModelRefs };

//# sourceMappingURL=tui-scoped-models.js.map