// #region AssistantApi [C:3] [TYPE Module] [SEMANTICS assistant, api, chat, session, history]
// @BRIEF API client for assistant chat — message sending, conversation management, confirmation operations, and history retrieval.
// @LAYER API
// @RELATION DEPENDS_ON -> [ApiModule]
// @PRE All requests go through requestApi wrapper (never native fetch).
// @POST Returns typed API responses or throws normalized errors.

import { requestApi } from '$lib/api';

// #region sendAssistantMessage [C:2] [TYPE Function] [SEMANTICS assistant, chat, message]
// @BRIEF Send a user message to the assistant orchestrator endpoint.
// @PRE payload.message is a non-empty string.
// @POST Returns assistant response object with deterministic state.
// @RELATION DEPENDS_ON -> [ApiModule.requestApi]
export function sendAssistantMessage<T = unknown>(payload: { message: string; [k: string]: unknown }): Promise<T> {
	return requestApi<T>('/assistant/messages', 'POST', payload);
}
// #endregion sendAssistantMessage

// #region buildAssistantSeedMessage [C:1] [TYPE Function] [SEMANTICS assistant, seed, prompt]
// @BRIEF Compose visible assistant seed text from context label and prompt body.
// @PRE prompt contains the user-visible request.
// @POST Returns trimmed seed message string for prefilled input.
export function buildAssistantSeedMessage({ label = '', prompt = '' }: { label?: string; prompt?: string } = {}): string {
	const normalizedLabel = String(label || '').trim();
	const normalizedPrompt = String(prompt || '').trim();
	if (normalizedLabel && normalizedPrompt) {
		return `${normalizedLabel}: ${normalizedPrompt}`;
	}
	return normalizedPrompt || normalizedLabel;
}
// #endregion buildAssistantSeedMessage

// #region confirmAssistantOperation [C:2] [TYPE Function] [SEMANTICS assistant, confirm, operation]
// @BRIEF Confirm a pending risky assistant operation.
// @PRE confirmationId references an existing pending token.
// @POST Returns execution response (started/success/failed).
// @RELATION DEPENDS_ON -> [ApiModule.requestApi]
export function confirmAssistantOperation<T = unknown>(confirmationId: string): Promise<T> {
	return requestApi<T>(`/assistant/confirmations/${confirmationId}/confirm`, 'POST');
}
// #endregion confirmAssistantOperation

// #region cancelAssistantOperation [C:2] [TYPE Function] [SEMANTICS assistant, cancel, operation]
// @BRIEF Cancel a pending risky assistant operation.
// @PRE confirmationId references an existing pending token.
// @POST Operation is cancelled and cannot be executed by this token.
// @RELATION DEPENDS_ON -> [ApiModule.requestApi]
export function cancelAssistantOperation<T = unknown>(confirmationId: string): Promise<T> {
	return requestApi<T>(`/assistant/confirmations/${confirmationId}/cancel`, 'POST');
}
// #endregion cancelAssistantOperation

// #region getAssistantHistory [C:2] [TYPE Function] [SEMANTICS assistant, history, pagination]
// @BRIEF Retrieve paginated assistant conversation history.
// @PRE page/pageSize are positive integers.
// @POST Returns a paginated payload with history items.
// @RELATION DEPENDS_ON -> [ApiModule.requestApi]
export function getAssistantHistory<T = unknown>(page: number = 1, pageSize: number = 20, conversationId: string | null = null, fromLatest: boolean = false): Promise<T> {
	const params = new URLSearchParams({ page: String(page), page_size: String(pageSize) });
	if (conversationId) {
		params.append('conversation_id', conversationId);
	}
	if (fromLatest) {
		params.append('from_latest', 'true');
	}
	return requestApi<T>(`/assistant/history?${params.toString()}`, 'GET');
}
// #endregion getAssistantHistory

// #region getAssistantConversations [C:2] [TYPE Function] [SEMANTICS assistant, conversations, sidebar]
// @BRIEF Retrieve paginated conversation list for assistant sidebar/history switcher.
// @PRE page/pageSize are positive integers.
// @POST Returns paginated conversation summaries.
// @RELATION DEPENDS_ON -> [ApiModule.requestApi]
export function getAssistantConversations<T = unknown>(
	page: number = 1,
	pageSize: number = 20,
	includeArchived: boolean = false,
	search: string = '',
	archivedOnly: boolean = false,
): Promise<T> {
	const params = new URLSearchParams({ page: String(page), page_size: String(pageSize) });
	if (includeArchived) {
		params.append('include_archived', 'true');
	}
	if (archivedOnly) {
		params.append('archived_only', 'true');
	}
	if (search?.trim()) {
		params.append('search', search.trim());
	}
	return requestApi<T>(`/assistant/conversations?${params.toString()}`, 'GET');
}
// #endregion getAssistantConversations

// #region deleteAssistantConversation [C:2] [TYPE Function] [SEMANTICS assistant, conversation, delete]
// @BRIEF Soft-delete or hard-delete a conversation.
// @PRE conversationId string is provided.
// @POST Returns success status.
// @RELATION DEPENDS_ON -> [ApiModule.requestApi]
export function deleteAssistantConversation<T = unknown>(conversationId: string): Promise<T> {
	return requestApi<T>(`/assistant/conversations/${conversationId}`, 'DELETE');
}
// #endregion deleteAssistantConversation
// #endregion AssistantApi
