import { isRecord } from './guards';
import { parseTimelineEvent } from './types';
import type { TimelineEvent } from './types';

export type SearchScope = { kind: 'room'; room_id: string } | { kind: 'rooms'; room_ids: string[] } | { kind: 'all' };

export interface ScopeOption {
  label: string;
  scope: SearchScope;
}

export interface SearchHit {
  room_id: string;
  event_id: string;
  timestamp_ms: number;
  event: TimelineEvent;
  ranges: [number, number][];
}

export type SearchBackfill = 'Waiting' | 'Running' | 'Paused' | 'Complete' | 'Disabled' | { Failed: string };

export interface RoomSearchCoverage {
  room_id: string;
  oldest_indexed_ms: number | null;
  start_reached: boolean;
  backfill: SearchBackfill;
}

export interface SearchCoverage {
  rooms: RoomSearchCoverage[];
  persistent: boolean;
  undecrypted: number;
}

export interface SearchPage {
  hits: SearchHit[];
  next: string | null;
  coverage: SearchCoverage;
}

export interface SearchSession {
  search_id: string;
  page: SearchPage;
}

/** The wire form of a scope, as macltok's externally tagged enum. */
export function scopeWire(scope: SearchScope): unknown {
  if (scope.kind === 'room') return { Room: scope.room_id };
  if (scope.kind === 'rooms') return { Rooms: scope.room_ids };
  return 'All';
}

/** macltok's matches are utf-8 byte ranges, so they're mapped back to string offsets against the body. */
function parseRanges(raw: unknown, body: string): [number, number][] {
  if (!Array.isArray(raw)) return [];
  const bytes = new TextEncoder().encode(body);
  const decoder = new TextDecoder();
  const offset = (byte: number) => decoder.decode(bytes.subarray(0, byte)).length;
  return raw.flatMap((range) =>
    isRecord(range) && typeof range['start'] === 'number' && typeof range['end'] === 'number'
      ? [[offset(range['start']), offset(range['end'])] as [number, number]]
      : []
  );
}

function hitBody(event: TimelineEvent): string {
  const content = event.content;
  if (content.kind === 'Message') return content.message.body;
  return '';
}

function parseHit(raw: unknown): SearchHit | null {
  if (!isRecord(raw) || typeof raw['room_id'] !== 'string' || typeof raw['event_id'] !== 'string' || !isRecord(raw['event'])) return null;
  const event = parseTimelineEvent(raw['event']);
  return {
    room_id: raw['room_id'],
    event_id: raw['event_id'],
    timestamp_ms: typeof raw['timestamp_ms'] === 'number' ? raw['timestamp_ms'] : event.timestamp_ms,
    event,
    ranges: parseRanges(raw['matches'], hitBody(event))
  };
}

function parseBackfill(raw: unknown): SearchBackfill {
  if (raw === 'Waiting' || raw === 'Running' || raw === 'Paused' || raw === 'Complete' || raw === 'Disabled') return raw;
  if (isRecord(raw) && isRecord(raw['Failed']) && typeof raw['Failed']['message'] === 'string') return { Failed: raw['Failed']['message'] };
  return 'Waiting';
}

function parseRoomCoverage(raw: unknown): RoomSearchCoverage | null {
  if (!isRecord(raw) || typeof raw['room_id'] !== 'string') return null;
  return {
    room_id: raw['room_id'],
    oldest_indexed_ms: typeof raw['oldest_indexed_ms'] === 'number' ? raw['oldest_indexed_ms'] : null,
    start_reached: raw['start_reached'] === true,
    backfill: parseBackfill(raw['backfill'])
  };
}

function parseCoverage(raw: unknown): SearchCoverage {
  if (!isRecord(raw)) return { rooms: [], persistent: false, undecrypted: 0 };
  return {
    rooms: Array.isArray(raw['rooms']) ? raw['rooms'].flatMap((room) => parseRoomCoverage(room) ?? []) : [],
    persistent: raw['persistent'] === true,
    undecrypted: typeof raw['undecrypted'] === 'number' ? raw['undecrypted'] : 0
  };
}

export function parseSearchPage(raw: unknown): SearchPage | null {
  if (!isRecord(raw) || !Array.isArray(raw['hits'])) return null;
  return {
    hits: raw['hits'].flatMap((hit) => parseHit(hit) ?? []),
    next: typeof raw['next_cursor'] === 'string' ? raw['next_cursor'] : null,
    coverage: parseCoverage(raw['coverage'])
  };
}

export function parseSearchSession(raw: unknown): SearchSession | null {
  if (!isRecord(raw) || typeof raw['search_id'] !== 'string') return null;
  const page = parseSearchPage(raw['page']);
  return page ? { search_id: raw['search_id'], page } : null;
}

/** Hits grouped by room, keeping the order in which each room first appears. */
export function groupByRoom(hits: SearchHit[]): { room_id: string; hits: SearchHit[] }[] {
  const groups = new Map<string, SearchHit[]>();
  for (const hit of hits) {
    const list = groups.get(hit.room_id);
    if (list) list.push(hit);
    else groups.set(hit.room_id, [hit]);
  }
  return [...groups].map(([room_id, list]) => ({ room_id, hits: list }));
}
