import { theme } from "../theme.js";
import { createSkillsAutocompleteProvider } from "../tui-skills-autocomplete.js";
import { clearTuiToolRenderers } from "./tool-renderers.js";
import { createTuiExtensionHost, invokeTuiExtensionRegistrars } from "./host.js";
import { TuiExtensionSurface } from "./surface.js";
import { CombinedAutocompleteProvider } from "@earendil-works/pi-tui";
//#region src/tui/extension-host/runtime.ts
var ChainedAutocompleteProvider = class {
	constructor(primary, extraProviders, extensionSlashCommands, getSessionKey, cwd) {
		this.primary = primary;
		this.extraProviders = extraProviders;
		this.extensionSlashCommands = extensionSlashCommands;
		this.getSessionKey = getSessionKey;
		this.cwd = cwd;
	}
	async getSuggestions(lines, cursorLine, cursorCol, options) {
		const primary = await this.primary.getSuggestions(lines, cursorLine, cursorCol, options);
		const beforeCursor = (lines[cursorLine] ?? "").slice(0, cursorCol);
		const slashMatch = beforeCursor.match(/^\/([\w-]*)$/);
		if (slashMatch && this.extensionSlashCommands.length > 0) {
			const query = (slashMatch[1] ?? "").toLowerCase();
			const prefix = `/${slashMatch[1] ?? ""}`;
			const items = this.extensionSlashCommands.filter((c) => !query || c.name.startsWith(query)).map((c) => ({
				value: `/${c.name}`,
				label: c.name,
				description: c.description
			}));
			if (items.length > 0) {
				const merged = primary?.items ? [...primary.items, ...items] : items;
				const seen = /* @__PURE__ */ new Set();
				return {
					prefix,
					items: merged.filter((item) => {
						if (seen.has(item.value)) return false;
						seen.add(item.value);
						return true;
					}).slice(0, 30)
				};
			}
		}
		const atMatch = beforeCursor.match(/@([\w.-]*)$/);
		if (!atMatch) return primary;
		const query = atMatch[1] ?? "";
		const prefix = `@${query}`;
		const sessionKey = this.getSessionKey();
		const items = [];
		for (const provider of this.extraProviders) {
			const suggestions = await provider(query, {
				cwd: this.cwd,
				sessionKey
			});
			for (const s of suggestions) items.push({
				value: `@${s.name}`,
				label: s.name,
				description: s.description
			});
		}
		if (items.length === 0) return primary;
		return {
			prefix,
			items: (query ? items.filter((item) => item.label.toLowerCase().includes(query.toLowerCase())) : items).slice(0, 20)
		};
	}
	applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
		if (prefix.startsWith("@")) {
			const line = lines[cursorLine] ?? "";
			const start = line.slice(0, cursorCol).length - prefix.length;
			const nextLine = line.slice(0, start) + item.value + line.slice(cursorCol);
			const nextLines = [...lines];
			nextLines[cursorLine] = nextLine;
			return {
				lines: nextLines,
				cursorLine,
				cursorCol: start + item.value.length
			};
		}
		return this.primary.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
	}
	shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
		return this.primary.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? false;
	}
};
function notifyInChatLog(chatLog, tui, message, level) {
	const prefix = level === "error" ? theme.error("✖ ") : level === "warn" ? "⚠ " : "";
	chatLog.addSystem(`${prefix}${message}`);
	tui.requestRender();
}
function suggestionsToAutocompleteItems(suggestions) {
	return suggestions.map((s) => ({
		value: `@${s.name}`,
		label: s.name,
		description: s.description
	}));
}
function createTuiExtensionRuntime(opts) {
	const surface = new TuiExtensionSurface();
	const slashCommands = [];
	const autocompleteProviders = [createSkillsAutocompleteProvider()];
	const disposers = [];
	const chainedProvider = new ChainedAutocompleteProvider(new CombinedAutocompleteProvider(opts.baseSlashCommands.map((c) => ({
		name: c.name,
		description: c.description
	})), opts.cwd, opts.fdPath), autocompleteProviders, slashCommands, () => opts.getState().currentSessionKey, opts.cwd);
	const invalidate = () => {
		opts.header.setExtensionLines(surface.getHeaderLines());
		opts.bottomBar.setExtensionLines(surface.getFooterLines());
		opts.bottomBar.setExtensionStatusParts(surface.getStatusParts());
		opts.onInvalidate();
	};
	const createHost = (extensionId) => createTuiExtensionHost({
		extensionId,
		surface,
		getSessionKey: () => opts.getState().currentSessionKey,
		notify: (message, level) => notifyInChatLog(opts.chatLog, opts.tui, message, level),
		showOverlay: opts.openOverlay,
		hideOverlay: opts.closeOverlay,
		onAutocompleteProviderAdded: (provider) => {
			autocompleteProviders.push(provider);
			return () => {
				const idx = autocompleteProviders.indexOf(provider);
				if (idx >= 0) autocompleteProviders.splice(idx, 1);
			};
		},
		onSlashCommandAdded: (name, description, handler) => {
			const entry = {
				name: name.replace(/^\//, "").toLowerCase(),
				description,
				handler
			};
			slashCommands.push(entry);
			return () => {
				const idx = slashCommands.indexOf(entry);
				if (idx >= 0) slashCommands.splice(idx, 1);
			};
		},
		onInvalidate: invalidate
	});
	return {
		surface,
		slashCommands,
		autocompleteProvider: chainedProvider,
		async activate() {
			await invokeTuiExtensionRegistrars(opts.registry?.getTuiRegistrations() ?? [], createHost, (extensionId, errorMessage) => {
				notifyInChatLog(opts.chatLog, opts.tui, `[${extensionId}] TUI init failed: ${errorMessage}`, "error");
			});
			invalidate();
		},
		dispose() {
			for (const dispose of disposers) dispose();
			disposers.length = 0;
			clearTuiToolRenderers();
			surface.headerWidgets.clear();
			surface.footerWidgets.clear();
			surface.statusSlots.clear();
		}
	};
}
//#endregion
export { createTuiExtensionRuntime, suggestionsToAutocompleteItems };

//# sourceMappingURL=runtime.js.map