// Backend-agnostic API surface. Every call forwards to whichever transport
// this build was compiled for, hosted (fetch + SSE) or on-device (worker).
import type { EventContext, EventContextPage, MemberSummary, RoomSummary } from './types';
import type { Emote } from './emotes';
import type { MentionKey, MentionsBoundary, MentionsPage, SavedMentionContext } from './mentions-model';
export { mentionKey, parseMentionsPage, parseSavedMentionContext, parseMentionsUpdate } from './mentions-model';
export type { MentionKey, MentionReason, MentionCaptureState, MentionEntry, MentionCoverage, MentionGap, MentionsBoundary, MentionsPage, SavedMentionContext, MentionsUpdate } from './mentions-model';
import { formatBody } from './markdown';
import { mentionedUserIds, type Mention } from './mentions';
import { HttpTransport } from './transport-http';
import { parseSearchPage, scopeWire, type SearchPage, type SearchScope } from './search-model';
import type { CommandRequest, SendKind, SessionInfo, Transport, VerifyAction } from './transport';
export type { HistoryRequest } from './transport';
import { createDeviceTransport } from 'malice:device-transport';

import { ApiError } from './transport';
export { ApiError } from './transport';
export type { SessionInfo, SoftLogout, VerifyAction } from './transport';

function createTransport(): Transport {
  if (import.meta.env.VITE_MALICE_TARGET === 'device') return createDeviceTransport();
  return new HttpTransport();
}

const transport: Transport = createTransport();

export function getSession(): Promise<SessionInfo> {
  return transport.getSession();
}

export function login(homeserver: string, username: string, password: string): Promise<{ user_id: string }> {
  return transport.login(homeserver, username, password);
}

export function logout(): Promise<void> {
  return transport.logout();
}

export function getRooms(): Promise<{ rooms: RoomSummary[] }> {
  return transport.getRooms();
}

export const openRoom = (room_id: string) => transport.openRoom(room_id);
export const closeRoom = (room_id: string) => transport.closeRoom(room_id);
export const sendMessage = (
  room_id: string,
  body: string,
  reply_to: string | null = null,
  mentions: Mention[] = [],
  kind: SendKind = 'text',
  emotes: Emote[] = [],
  thread_root: string | null = null
) => transport.sendMessage(room_id, body, formatBody(body, mentions, true, emotes), reply_to, mentionedUserIds(mentions), kind, thread_root);
export const runCommand = (request: CommandRequest) => transport.command(request);
export const uploadAvatar = (file: File) => transport.uploadAvatar(file);
export const uploadRoomAvatar = (room_id: string, file: File) => transport.uploadRoomAvatar(room_id, file);
export const uploadMedia = (file: File) => transport.uploadMedia(file);
export const paginateRoom = (room_id: string, thread_root: string | null = null) => transport.paginateRoom(room_id, thread_root);
export const eventContext = (room_id: string, event_id: string, limit?: number): Promise<EventContext> =>
  transport.eventContext(room_id, event_id, limit);
export const eventContextBefore = (room_id: string, event_id: string, from: string, limit?: number): Promise<EventContextPage> =>
  transport.eventContextBefore(room_id, event_id, from, limit);
export const eventContextAfter = (room_id: string, event_id: string, from: string, limit?: number): Promise<EventContextPage> =>
  transport.eventContextAfter(room_id, event_id, from, limit);
export const mentionsPage = (cursor: string | null = null, limit = 50): Promise<MentionsPage> => transport.mentionsPage(cursor, limit);
export const mentionContext = (room_id: string, event_id: string): Promise<SavedMentionContext> => transport.mentionContext(room_id, event_id);
export const retryMentionContext = (room_id: string, event_id: string): Promise<SavedMentionContext> => transport.retryMentionContext(room_id, event_id);
export const setMentionsRead = (keys: MentionKey[], read: boolean) => transport.setMentionsRead(keys, read);
export const markMentionsReadThrough = (boundary: MentionsBoundary) => transport.markMentionsReadThrough(boundary);
export const recoverMentions = () => transport.recoverMentions();
export async function searchMessages(query: string, scope: SearchScope, cursor: string | null = null, limit = 30): Promise<SearchPage> {
  let raw: unknown;
  try {
    raw = await transport.command({ op: 'search', query, scope: scopeWire(scope), cursor, limit });
  } catch (e) {
    if (e instanceof ApiError && (e.status === 400 || e.status === 422)) throw new ApiError(400, "Search isn't available yet");
    throw e;
  }
  const page = parseSearchPage(raw);
  if (!page) throw new ApiError(502, 'Invalid search response');
  return page;
}
export const startRecentHistory = (room_id: string): Promise<void> => transport.startRecentHistory(room_id);
export const fillHistoryGap = (room_id: string, gap_id: string): Promise<void> => transport.fillHistoryGap(room_id, gap_id);
export const setTyping = (room_id: string, typing: boolean) => transport.setTyping(room_id, typing);
export const getAccountData = (eventType: string) => transport.getAccountData(eventType);
export const getUrlPreview = (room_id: string, url: string) => transport.getUrlPreview(room_id, url);
export const setAccountData = (eventType: string, content: Record<string, unknown>) =>
  transport.setAccountData(eventType, content);

export function joinRoom(room: string): Promise<{ room_id: string }> {
  return transport.joinRoom(room);
}

export function createRoom(name: string, topic?: string): Promise<{ room_id: string }> {
  return transport.createRoom(name, topic);
}

export const leaveRoom = (room_id: string) => transport.leaveRoom(room_id);
export const reactToMessage = (room_id: string, event_id: string, key: string, shortcode?: string, thread_root: string | null = null) =>
  transport.reactToMessage(room_id, event_id, key, shortcode, thread_root);
export const editMessage = (room_id: string, event_id: string, body: string, mentions: Mention[] = [], emotes: Emote[] = [], thread_root: string | null = null) =>
  transport.editMessage(room_id, event_id, body, formatBody(body, mentions, true, emotes), mentionedUserIds(mentions), thread_root);
export const markRead = (room_id: string, event_id: string, thread_root: string | null = null) => transport.markRead(room_id, event_id, thread_root);

export function getMembers(room_id: string): Promise<{ members: MemberSummary[] }> {
  return transport.getMembers(room_id);
}

/** Same URL shape in both builds: the hosted server and the device service worker both answer it. */
export function mediaUrl(mxc: string | null, size = 256): string | null {
  if (!mxc) return null;
  return `/api/media?mxc=${encodeURIComponent(mxc)}&size=${Math.max(16, Math.min(512, Math.round(size)))}`;
}

export function messageMediaUrl(mediaId: string, size: 'Thumbnail' | 'Full'): string {
  return `/api/message-media?media_id=${encodeURIComponent(mediaId)}&size=${size}`;
}

export function getProfile(): Promise<{ display_name: string | null; avatar_url: string | null }> {
  return transport.getProfile();
}

export function getSpaceChildren(room_id: string): Promise<{ room_ids: string[] }> {
  return transport.getSpaceChildren(room_id);
}

export function getEncryption(): Promise<{ state: unknown; verification: unknown }> {
  return transport.getEncryption();
}

export function recoverEncryption(recovery_key: string): Promise<void> {
  return transport.recoverEncryption(recovery_key);
}

export function startVerification(): Promise<void> {
  return transport.startVerification();
}

export function verifyEncryption(action: VerifyAction): Promise<void> {
  return transport.verifyEncryption(action);
}

export function uploadAttachment(
  room_id: string,
  file: File,
  caption: string | null = null,
  reply_to: string | null = null,
  mentions: Mention[] = [],
  emotes: Emote[] = [],
  thread_root: string | null = null
): Promise<void> {
  return transport.uploadAttachment(room_id, file, {
    caption,
    formatted_caption: caption ? formatBody(caption, mentions, true, emotes) : null,
    reply_to,
    mentions: mentionedUserIds(mentions),
    thread_root
  });
}

export function subscribeEvents(onEvent: (data: string) => void, onDisconnect: () => void): () => void {
  return transport.subscribeEvents(onEvent, onDisconnect);
}
