import { isRecord } from './guards';
import { parseTimelineItem } 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 interface SearchCoverage {
  room_id: string;
  oldest_indexed_ms: number | null;
  reached_start: boolean;
}

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

/** 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';
}

function parseRanges(raw: unknown): [number, number][] {
  if (!Array.isArray(raw)) return [];
  return raw.flatMap((range) =>
    Array.isArray(range) && typeof range[0] === 'number' && typeof range[1] === 'number' ? [[range[0], range[1]] as [number, number]] : []
  );
}

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

function parseCoverage(raw: unknown): SearchCoverage | 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,
    reached_start: raw['reached_start'] === true
  };
}

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'] === 'string' ? raw['next'] : null,
    coverage: Array.isArray(raw['coverage']) ? raw['coverage'].flatMap((c) => parseCoverage(c) ?? []) : []
  };
}

/** 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 }));
}
