<script lang="ts">
	import { OverrideLevel, ToolType } from '$lib/proto/llm_multiverse/v1/common_pb';
	import type { SessionConfig } from '$lib/proto/llm_multiverse/v1/orchestrator_pb';
	import { SessionConfigSchema } from '$lib/proto/llm_multiverse/v1/orchestrator_pb';
	import { create } from '@bufbuild/protobuf';

	let {
		config,
		onConfigChange
	}: { config: SessionConfig; onConfigChange: (config: SessionConfig) => void } = $props();

	let newPermission = $state('');

	const toolTypes = [
		{ value: ToolType.MEMORY_READ, label: 'Memory Read' },
		{ value: ToolType.MEMORY_WRITE, label: 'Memory Write' },
		{ value: ToolType.WEB_SEARCH, label: 'Web Search' },
		{ value: ToolType.FS_READ, label: 'FS Read' },
		{ value: ToolType.FS_WRITE, label: 'FS Write' },
		{ value: ToolType.RUN_CODE, label: 'Run Code' },
		{ value: ToolType.RUN_SHELL, label: 'Run Shell' },
		{ value: ToolType.PACKAGE_INSTALL, label: 'Package Install' }
	];

	const overrideLevels = [
		{ value: OverrideLevel.NONE, label: 'None', description: 'Full enforcement' },
		{ value: OverrideLevel.RELAX, label: 'Relax', description: 'High-risk tools unlocked' },
		{ value: OverrideLevel.ALL, label: 'All', description: 'No enforcement' }
	];

	const isNonDefault = $derived(
		config.overrideLevel !== OverrideLevel.NONE ||
			config.disabledTools.length > 0 ||
			config.grantedPermissions.length > 0
	);

	function setOverrideLevel(level: OverrideLevel) {
		const updated = create(SessionConfigSchema, {
			...config,
			overrideLevel: level
		});
		onConfigChange(updated);
	}

	function toggleTool(tool: string) {
		const disabled = [...config.disabledTools];
		const idx = disabled.indexOf(tool);
		if (idx >= 0) {
			disabled.splice(idx, 1);
		} else {
			disabled.push(tool);
		}
		const updated = create(SessionConfigSchema, {
			...config,
			disabledTools: disabled
		});
		onConfigChange(updated);
	}

	function addPermission() {
		const trimmed = newPermission.trim();
		if (!trimmed || config.grantedPermissions.includes(trimmed)) return;
		const updated = create(SessionConfigSchema, {
			...config,
			grantedPermissions: [...config.grantedPermissions, trimmed]
		});
		onConfigChange(updated);
		newPermission = '';
	}

	function removePermission(perm: string) {
		const updated = create(SessionConfigSchema, {
			...config,
			grantedPermissions: config.grantedPermissions.filter((p) => p !== perm)
		});
		onConfigChange(updated);
	}

	function resetConfig() {
		onConfigChange(create(SessionConfigSchema, { overrideLevel: OverrideLevel.NONE }));
	}
</script>

<aside class="flex h-full w-72 flex-col border-l border-gray-200 bg-white">
	<div class="flex items-center justify-between border-b border-gray-200 px-4 py-3">
		<div class="flex items-center gap-2">
			<h2 class="text-sm font-semibold text-gray-900">Session Config</h2>
			{#if isNonDefault}
				<span class="h-2 w-2 rounded-full bg-amber-500" title="Non-default config active"></span>
			{/if}
		</div>
		<button
			type="button"
			onclick={resetConfig}
			class="text-xs text-gray-500 hover:text-gray-700"
		>
			Reset
		</button>
	</div>

	<div class="flex-1 overflow-y-auto p-4 space-y-5">
		<!-- Override Level -->
		<div>
			<p class="mb-2 text-xs font-medium text-gray-700">Override Level</p>
			<div class="space-y-1">
				{#each overrideLevels as level (level.value)}
					<button
						type="button"
						onclick={() => setOverrideLevel(level.value)}
						class="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm
							{config.overrideLevel === level.value
							? 'bg-blue-50 text-blue-700 ring-1 ring-blue-200'
							: 'text-gray-700 hover:bg-gray-50'}"
					>
						<span class="font-medium">{level.label}</span>
						<span class="text-xs text-gray-500">— {level.description}</span>
					</button>
				{/each}
			</div>
		</div>

		<!-- Disabled Tools -->
		<div>
			<p class="mb-2 text-xs font-medium text-gray-700">Disabled Tools</p>
			<div class="space-y-1">
				{#each toolTypes as tool (tool.value)}
					<label class="flex items-center gap-2 rounded px-2 py-1 text-sm hover:bg-gray-50">
						<input
							type="checkbox"
							checked={config.disabledTools.includes(tool.label)}
							onchange={() => toggleTool(tool.label)}
							class="rounded border-gray-300 text-blue-600"
						/>
						<span class="text-gray-700">{tool.label}</span>
					</label>
				{/each}
			</div>
		</div>

		<!-- Granted Permissions -->
		<div>
			<p class="mb-2 text-xs font-medium text-gray-700">Granted Permissions</p>
			<div class="flex gap-1">
				<input
					type="text"
					bind:value={newPermission}
					onkeydown={(e) => { if (e.key === 'Enter') addPermission(); }}
					placeholder="agent_type:tool"
					class="flex-1 rounded-lg border border-gray-300 px-2 py-1.5 text-xs focus:border-blue-500 focus:outline-none"
				/>
				<button
					type="button"
					onclick={addPermission}
					class="rounded-lg bg-gray-100 px-2 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-200"
				>
					Add
				</button>
			</div>
			{#if config.grantedPermissions.length > 0}
				<div class="mt-2 space-y-1">
					{#each config.grantedPermissions as perm (perm)}
						<div class="flex items-center justify-between rounded bg-gray-50 px-2 py-1">
							<code class="text-xs text-gray-700">{perm}</code>
							<button
								type="button"
								onclick={() => removePermission(perm)}
								class="text-xs text-gray-400 hover:text-red-500"
							>
								✕
							</button>
						</div>
					{/each}
				</div>
			{/if}
		</div>
	</div>
</aside>
