<script lang="ts">
	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import { resolveRoute } from '$app/paths';
	import type { ChatMessage } from '$lib/types';
	import type { SubagentResult } from '$lib/proto/llm_multiverse/v1/common_pb';
	import { OverrideLevel } 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';
	import MessageList from '$lib/components/MessageList.svelte';
	import MessageInput from '$lib/components/MessageInput.svelte';
	import OrchestrationProgress from '$lib/components/OrchestrationProgress.svelte';
	import ThinkingSection from '$lib/components/ThinkingSection.svelte';
	import FinalResult from '$lib/components/FinalResult.svelte';
	import SessionSidebar from '$lib/components/SessionSidebar.svelte';
	import ConfigSidebar from '$lib/components/ConfigSidebar.svelte';
	import ThemeToggle from '$lib/components/ThemeToggle.svelte';
	import { processRequest, OrchestratorError } from '$lib/services/orchestrator';
	import { OrchestrationState } from '$lib/proto/llm_multiverse/v1/orchestrator_pb';
	import { sessionStore } from '$lib/stores/sessions.svelte';
	import { memoryStore } from '$lib/stores/memory.svelte';
	import { auditStore } from '$lib/stores/audit.svelte';

	let messages: ChatMessage[] = $state([]);
	let isStreaming = $state(false);
	let error: string | null = $state(null);
	let orchestrationState: OrchestrationState = $state(OrchestrationState.UNSPECIFIED);
	let intermediateResult: string = $state('');
	let finalResult: SubagentResult | null = $state(null);
	let sessionConfig: SessionConfig = $state(
		create(SessionConfigSchema, { overrideLevel: OverrideLevel.NONE })
	);
	let showConfig = $state(false);
	const lineageHref = resolveRoute('/lineage');
	const memoryHref = resolveRoute('/memory');
	const auditHref = resolveRoute('/audit');

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

	function navigateToSession(sessionId: string, replace = false) {
		const url = `${resolveRoute('/chat')}?session=${sessionId}`;
		// eslint-disable-next-line svelte/no-navigation-without-resolve
		goto(url, { replaceState: replace });
	}

	$effect(() => {
		const sessionParam = $page.url.searchParams.get('session');
		const session = sessionStore.getOrCreateSession(sessionParam ?? undefined);
		messages = [...session.messages];
		if (!sessionParam || sessionParam !== session.id) {
			navigateToSession(session.id, true);
		}
	});

	function handleNewChat() {
		const session = sessionStore.createSession();
		messages = [];
		error = null;
		finalResult = null;
		navigateToSession(session.id);
	}

	function handleSelectSession(id: string) {
		sessionStore.switchSession(id);
		const session = sessionStore.activeSession;
		if (session) {
			messages = [...session.messages];
			error = null;
			finalResult = null;
			navigateToSession(id);
		}
	}

	async function handleSend(content: string) {
		error = null;
		orchestrationState = OrchestrationState.UNSPECIFIED;
		intermediateResult = '';
		finalResult = null;

		const sessionId = sessionStore.activeSessionId!;
		let lastAuditState = OrchestrationState.UNSPECIFIED;

		const userMessage: ChatMessage = {
			id: crypto.randomUUID(),
			role: 'user',
			content,
			timestamp: new Date()
		};
		messages.push(userMessage);

		const assistantMessage: ChatMessage = {
			id: crypto.randomUUID(),
			role: 'assistant',
			content: '',
			timestamp: new Date()
		};
		messages.push(assistantMessage);

		sessionStore.updateMessages(sessionId, messages);
		isStreaming = true;

		try {
			for await (const response of processRequest(sessionId, content, sessionConfig)) {
				orchestrationState = response.state;

				// Capture state changes to the audit log
				if (response.state !== lastAuditState) {
					const stateLabel = OrchestrationState[response.state] ?? String(response.state);
					auditStore.addEvent(sessionId, {
						eventType: 'state_change',
						details: response.message || `State changed to ${stateLabel}`,
						state: stateLabel
					});
					lastAuditState = response.state;
				}

				if (response.intermediateResult) {
					intermediateResult = response.intermediateResult;
				}
				if (response.finalResult) {
					finalResult = response.finalResult;
					if (response.finalResult.newMemoryCandidates.length > 0) {
						memoryStore.addCandidates(
							sessionId,
							response.finalResult.newMemoryCandidates.map((mc) => ({
								content: mc.content,
								source: mc.source,
								confidence: mc.confidence
							}))
						);
					}
				}
				const idx = messages.length - 1;
				messages[idx] = {
					...messages[idx],
					content: response.message
				};
			}
		} catch (err) {
			const msg =
				err instanceof OrchestratorError
					? `Error (${err.code}): ${err.message}`
					: 'An unexpected error occurred';
			error = msg;
			auditStore.addEvent(sessionId, {
				eventType: 'error',
				details: msg
			});
			const idx = messages.length - 1;
			messages[idx] = {
				...messages[idx],
				content: `\u26A0 ${msg}`
			};
		} finally {
			isStreaming = false;
			sessionStore.updateMessages(sessionId, messages);
		}
	}
</script>

<div class="flex h-screen bg-white dark:bg-gray-900">
	<SessionSidebar onSelectSession={handleSelectSession} onNewChat={handleNewChat} />

	<div class="flex flex-1 flex-col">
		<header class="flex items-center justify-between border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-4 py-3">
			<h1 class="text-lg font-semibold text-gray-900 dark:text-gray-100">Chat</h1>
			<div class="flex items-center gap-2">
			<!-- eslint-disable svelte/no-navigation-without-resolve -- resolveRoute is resolve; plugin does not recognize the alias -->
			<a
				href={lineageHref}
				class="rounded-lg px-2.5 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-gray-100"
			>
				Lineage
			</a>
			<a
				href={memoryHref}
				class="rounded-lg px-2.5 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-gray-100"
			>
				Memory
			</a>
			<a
				href={auditHref}
				class="rounded-lg px-2.5 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-gray-100"
			>
				Audit
			</a>
			<!-- eslint-enable svelte/no-navigation-without-resolve -->
			<ThemeToggle />
			<button
				type="button"
				onclick={() => (showConfig = !showConfig)}
				class="flex items-center gap-1 rounded-lg px-2.5 py-1.5 text-sm
					{showConfig ? 'bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300' : 'bg-gray-100 text-gray-700 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600'}"
			>
				{#if isNonDefaultConfig}
					<span class="h-2 w-2 rounded-full bg-amber-500"></span>
				{/if}
				Config
			</button>
			</div>
		</header>

		<MessageList {messages} />

		{#if isStreaming}
			<OrchestrationProgress state={orchestrationState} />
			<ThinkingSection content={intermediateResult} />
		{/if}

		{#if isStreaming && messages.length > 0 && messages[messages.length - 1].content === ''}
			<div class="flex justify-start px-4 pb-2">
				<div class="flex items-center gap-1.5 rounded-2xl bg-gray-200 dark:bg-gray-700 px-4 py-2.5">
					<span class="h-2 w-2 animate-bounce rounded-full bg-gray-500 dark:bg-gray-400 [animation-delay:0ms]"
					></span>
					<span
						class="h-2 w-2 animate-bounce rounded-full bg-gray-500 dark:bg-gray-400 [animation-delay:150ms]"
					></span>
					<span
						class="h-2 w-2 animate-bounce rounded-full bg-gray-500 dark:bg-gray-400 [animation-delay:300ms]"
					></span>
				</div>
			</div>
		{/if}

		{#if finalResult && !isStreaming}
			<FinalResult result={finalResult} />
		{/if}

		{#if error}
			<div class="mx-4 mb-2 rounded-lg bg-red-50 dark:bg-red-900/30 px-4 py-2 text-sm text-red-600 dark:text-red-400">
				{error}
			</div>
		{/if}

		<MessageInput onSend={handleSend} disabled={isStreaming} />
	</div>

	{#if showConfig}
		<ConfigSidebar
			config={sessionConfig}
			onConfigChange={(c) => (sessionConfig = c)}
		/>
	{/if}
</div>
