import type { CommandRequest, PackTarget } from './transport';
import type { CloneSource } from './pack-clone';
import type { ImagePack, ImagePacks, PackImage, PackUsage, RoomSummary } from './types';

export interface PackChoice {
  label: string;
  target: PackTarget;
  pack: ImagePack | null;
}

export function packTarget(pack: ImagePack): PackTarget {
  if (pack.source === 'User') return { kind: 'user' };
  return { kind: 'room', room_id: pack.source.Room.room_id, state_key: pack.source.Room.state_key };
}

export function packLabel(pack: ImagePack, roomName: (roomId: string) => string): string {
  if (pack.display_name) return pack.display_name;
  if (pack.source === 'User') return 'Your pack';
  return roomName(pack.source.Room.room_id);
}

export function allPacks(packs: ImagePacks): ImagePack[] {
  const seen = new Set<string>();
  const out: ImagePack[] = [];
  for (const pack of [...packs.global, ...Object.values(packs.rooms).flat()]) {
    if (seen.has(pack.id)) continue;
    seen.add(pack.id);
    out.push(pack);
  }
  return out;
}

export function packsForRoom(
  packs: ImagePacks,
  roomId: string | null,
  rooms: Pick<RoomSummary, 'room_id' | 'parent_spaces' | 'children' | 'space'>[] = []
): ImagePack[] {
  const seen = new Set<string>();
  const out: ImagePack[] = [];
  const add = (pack: ImagePack) => {
    if (seen.has(pack.id) || pack.images.length === 0) return;
    seen.add(pack.id);
    out.push(pack);
  };
  for (const pack of packs.global) if (pack.source === 'User') add(pack);
  if (roomId) {
    const visited = new Set<string>();
    const queue = [roomId];
    for (const id of queue) {
      if (visited.has(id)) continue;
      visited.add(id);
      for (const pack of packs.rooms[id] ?? []) add(pack);
      const room = rooms.find((entry) => entry.room_id === id);
      queue.push(...(room?.parent_spaces ?? []));
      for (const space of rooms) {
        if (space.space && space.children.includes(id)) queue.push(space.room_id);
      }
    }
  }
  for (const pack of packs.global) add(pack);
  return out;
}

/** Packs you can write to, with your own pack first even before it exists. */
export function editableChoices(packs: ImagePacks, roomName: (roomId: string) => string): PackChoice[] {
  const all = allPacks(packs);
  const user = all.find((p) => p.source === 'User') ?? null;
  const choices: PackChoice[] = [{ label: user?.display_name ?? 'Your pack', target: { kind: 'user' }, pack: user }];
  for (const pack of all) {
    if (pack.source === 'User' || !pack.editable) continue;
    choices.push({ label: `${packLabel(pack, roomName)} · ${roomName(pack.source.Room.room_id)}`, target: packTarget(pack), pack });
  }
  return choices;
}

export function hasUsage(image: PackImage, usage: PackUsage): boolean {
  return image.usage.length === 0 || image.usage.includes(usage);
}

export function stickersOf(pack: ImagePack): PackImage[] {
  return pack.images.filter((image) => hasUsage(image, 'Sticker'));
}

export function reactionShortcode(key: string, shortcode: string | undefined, packs: ImagePack[]): string | undefined {
  if (!key.startsWith('mxc://')) return undefined;
  const provided = shortcode?.trim();
  if (provided) return provided;
  for (const pack of packs) {
    const image = pack.images.find((item) => item.reaction_key === key);
    if (image) return image.shortcode;
  }
  return undefined;
}

export function findSticker(packs: ImagePack[], shortcode: string): { pack: ImagePack; sticker: PackImage } {
  const name = shortcode.toLowerCase();
  const matches = packs.flatMap((pack) => stickersOf(pack)
    .filter((sticker) => sticker.shortcode.toLowerCase() === name)
    .map((sticker) => ({ pack, sticker })));
  if (matches.length === 0) throw new Error(`No sticker named ${shortcode} is available in this room`);
  if (matches.length > 1) throw new Error(`More than one sticker is named ${shortcode}, choose one from the sticker menu`);
  return matches[0];
}

/** A shortcode from a file name, unique within `taken`. */
export function shortcodeFor(filename: string, taken: Set<string>): string {
  const stem = filename.replace(/\.[^.]+$/, '');
  const base =
    stem
      .toLowerCase()
      .replace(/[^a-z0-9_-]+/g, '_')
      .replace(/^_+|_+$/g, '')
      .slice(0, 64) || 'image';
  let candidate = base;
  for (let n = 2; taken.has(candidate); n += 1) candidate = `${base}_${n}`;
  taken.add(candidate);
  return candidate;
}

export function validShortcode(code: string): boolean {
  return /^[^\s:]{1,100}$/.test(code);
}

export function packSlug(name: string): string {
  return (
    name
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/^-+|-+$/g, '')
      .slice(0, 48) || 'pack'
  );
}

export function freePackStateKey(packs: ImagePacks, roomId: string, name: string): string {
  const taken = new Set(allPacks(packs).flatMap((pack) =>
    pack.source !== 'User' && pack.source.Room.room_id === roomId ? [pack.source.Room.state_key] : []));
  const base = packSlug(name);
  let key = base;
  for (let n = 2; taken.has(key); n += 1) key = `${base}-${n}`;
  return key;
}

export function cloneRequest(
  source: CloneSource,
  to: PackTarget,
  usage: PackUsage[],
  displayName: string | null,
  destination: ImagePack | null
): CommandRequest {
  if (usage.length === 0) throw new Error('Choose at least one use for the copied images');
  if (source.kind === 'pack') {
    return { op: 'clone_pack', from_pack: source.pack.id, to, display_name: displayName, usage };
  }
  if (source.kind === 'image') {
    return { op: 'clone_pack_image', from_pack: source.pack.id, shortcode: source.image.shortcode, to, usage };
  }
  const taken = new Set(destination?.images.map((image) => image.shortcode) ?? []);
  return {
    op: 'clone_sticker', room_id: source.room_id, event_id: source.event_id, to,
    shortcode: shortcodeFor(source.body || 'sticker', taken), usage
  };
}

export interface CloneDestination {
  label: string;
  target: PackTarget;
  display_name: string | null;
}

/** Where a whole pack can be cloned to: merged into your pack, or as a new pack in a room you can edit. */
export function clonePackDestinations(
  pack: ImagePack,
  rooms: { room_id: string; name: string }[],
  roomName: (roomId: string) => string
): CloneDestination[] {
  const name = packLabel(pack, roomName);
  return [
    { label: 'Merge into your pack', target: { kind: 'user' }, display_name: null },
    ...rooms.map((room) => ({
      label: `New pack in ${room.name}`,
      target: { kind: 'room', room_id: room.room_id, state_key: packSlug(name) } as PackTarget,
      display_name: name
    }))
  ];
}
