// Three-way merge of two versions of a saved project (projects.ts). When
// another computer has saved since this one last did, the newer version
// is not simply loaded over the edits made here, nor are they kept as a
// separate copy: both are kept, in one plan. base is the snapshot this
// browser last knew the server to hold, mine the one on screen, theirs the
// server's newer one — and every difference is judged against base: a
// change made on one side only is a change, the same thing on both sides
// is no conflict, and a real collision (the same field changed to two
// different values within the same few seconds) goes to theirs, counted
// in `overridden` so the status line can say so.
//
// This works because the arrangement is pure data in maps keyed by random
// ids (ids.ts): two people adding tables or seating guests never touch the
// same key. The rules, applied recursively to any JSON value:
//
// - Records (rooms, tables, guests, groups, and the maps that hold them):
//   a key on one side only is an addition (not in base: kept) or a
//   deletion (in base: dropped — deletion wins over an edit, which then
//   counts as overridden when it was mine).
// - Arrays are ordered sets of ids (roomOrder, guestOrder, likes, group
//   members, chair lists): theirs is the order; what I added goes in after
//   its predecessor in my list, what I removed goes.
// - Anything else: mine if only I changed it, theirs otherwise.
// - Navigation (which room and step are open, each room's scroll and
//   zoom, savedAt) and the derived zIndex are never merged: mine, as on
//   screen. withNavigationOf does the same for a version taken in whole.
// - After the merge, one guest per chair: a chair two guests ended up on
//   keeps theirs.
//
// The result is a raw snapshot; the caller passes it through the normal
// read path (readPersistedSnapshot), whose normalisation prunes anything
// now dangling — a guest they removed whom I seated, a chair of a table
// they took away. Pure: no DOM, no globals, so it also runs in the Node
// tests (tests/worker/merge.test.js). The record/equality/copy helpers
// live in plainData.ts, shared with edits.ts.

type MergeRaw = DataRecord;
type MergeResult = { state: MergeRaw; overridden: number };

// Mine, never a conflict: navigation, the timestamp, and a table's zIndex,
// which every table-list render rewrites (tables.ts) on both computers.
const MERGE_NAVIGATION_KEYS = new Set([
  "savedAt",
  "currentRoomId",
  "currentStep",
  "zoom",
  "scrollLeft",
  "scrollTop",
  "zIndex",
]);

const mergeValues = (
  base: unknown,
  mine: unknown,
  theirs: unknown,
  tally: { overridden: number },
): unknown => {
  if (dataEqual(mine, theirs)) return cloneData(mine);
  if (dataEqual(mine, base)) return cloneData(theirs);
  if (dataEqual(theirs, base)) return cloneData(mine);
  // Both sides changed it, differently.
  if (isDataRecord(mine) && isDataRecord(theirs)) {
    return mergeRecords(isDataRecord(base) ? base : {}, mine, theirs, tally);
  }
  if (Array.isArray(mine) && Array.isArray(theirs)) {
    return mergeIdArrays(Array.isArray(base) ? base : [], mine, theirs);
  }
  tally.overridden += 1;
  return cloneData(theirs);
};

const mergeRecords = (
  base: MergeRaw,
  mine: MergeRaw,
  theirs: MergeRaw,
  tally: { overridden: number },
): MergeRaw => {
  const result: MergeRaw = {};
  const keys = new Set([...Object.keys(theirs), ...Object.keys(mine)]);
  for (const key of keys) {
    const inMine = key in mine;
    const inTheirs = key in theirs;
    const inBase = key in base;
    if (MERGE_NAVIGATION_KEYS.has(key)) {
      if (inMine) result[key] = cloneData(mine[key]);
      else if (inTheirs) result[key] = cloneData(theirs[key]);
      continue;
    }
    if (inMine && inTheirs) {
      if (
        key === "nextTableNumber" &&
        typeof mine[key] === "number" &&
        typeof theirs[key] === "number"
      ) {
        result[key] = Math.max(mine[key], theirs[key]);
      } else {
        result[key] = mergeValues(inBase ? base[key] : undefined, mine[key], theirs[key], tally);
      }
      continue;
    }
    if (inMine) {
      // Only mine: added here, or deleted there.
      if (!inBase) result[key] = cloneData(mine[key]);
      else if (!dataEqual(mine[key], base[key])) tally.overridden += 1;
      continue;
    }
    // Only theirs: added there, or deleted here.
    if (!inBase) result[key] = cloneData(theirs[key]);
  }
  return result;
};

const mergeIdArrays = (base: unknown[], mine: unknown[], theirs: unknown[]): unknown[] => {
  const baseKeys = new Set(base.map(listItemKey));
  const mineKeys = new Set(mine.map(listItemKey));
  // Theirs, minus what I removed.
  const result = theirs
    .filter((item) => {
      const key = listItemKey(item);
      return !(baseKeys.has(key) && !mineKeys.has(key));
    })
    .map(cloneData);
  const resultKeys = new Set(result.map(listItemKey));
  // Plus what I added, each after its predecessor in my list when that one
  // is in the result, else at the end.
  mine.forEach((item, index) => {
    const key = listItemKey(item);
    if (baseKeys.has(key) || resultKeys.has(key)) return;
    let insertAt = result.length;
    for (let before = index - 1; before >= 0; before--) {
      const position = result.findIndex(
        (candidate) => listItemKey(candidate) === listItemKey(mine[before]),
      );
      if (position !== -1) {
        insertAt = position + 1;
        break;
      }
    }
    result.splice(insertAt, 0, cloneData(item));
    resultKeys.add(key);
  });
  return result;
};

// One guest per chair, in every room: where the merge seated two guests on
// the same chair (each side seated its own there), theirs stays.
const mergeEnforceOneGuestPerChair = (
  state: MergeRaw,
  theirs: MergeRaw,
  tally: { overridden: number },
) => {
  if (!isDataRecord(state.allRooms)) return;
  const theirRooms = isDataRecord(theirs.allRooms) ? theirs.allRooms : {};
  for (const roomId of Object.keys(state.allRooms)) {
    const room = state.allRooms[roomId];
    if (!isDataRecord(room) || !isDataRecord(room.placement)) continue;
    const theirRoom = theirRooms[roomId];
    const theirPlacement =
      isDataRecord(theirRoom) && isDataRecord(theirRoom.placement) ? theirRoom.placement : {};
    const byChair = new Map<string, string[]>();
    for (const guestId of Object.keys(room.placement)) {
      const chairId = room.placement[guestId];
      if (typeof chairId !== "string") continue;
      byChair.set(chairId, [...(byChair.get(chairId) ?? []), guestId]);
    }
    for (const [chairId, guestIds] of byChair) {
      if (guestIds.length < 2) continue;
      const keep = guestIds.find((guestId) => theirPlacement[guestId] === chairId) ?? guestIds[0];
      for (const guestId of guestIds) {
        if (guestId === keep) continue;
        delete room.placement[guestId];
        tally.overridden += 1;
      }
    }
  }
};

// Theirs, with this screen's navigation: another computer's version taken
// in as it is (nothing edited here) must not move this one to the step and
// room the other person is on, nor scroll or zoom their room for them.
// The same keys the merge leaves to mine, copied over theirs — at the top,
// and in every room both have.
const copyNavigationKeys = (from: MergeRaw, to: MergeRaw) => {
  for (const key of MERGE_NAVIGATION_KEYS) {
    if (key in from) to[key] = cloneData(from[key]);
  }
};

const withNavigationOf = (mine: MergeRaw, theirs: MergeRaw): MergeRaw => {
  const result = cloneData(theirs);
  copyNavigationKeys(mine, result);
  if (isDataRecord(mine.allRooms) && isDataRecord(result.allRooms)) {
    for (const roomId of Object.keys(result.allRooms)) {
      const myRoom = mine.allRooms[roomId];
      const room = result.allRooms[roomId];
      if (isDataRecord(myRoom) && isDataRecord(room)) copyNavigationKeys(myRoom, room);
    }
  }
  return result;
};

const mergePersistedStates = (base: MergeRaw, mine: MergeRaw, theirs: MergeRaw): MergeResult => {
  const tally = { overridden: 0 };
  const state = mergeRecords(base, mine, theirs, tally);
  mergeEnforceOneGuestPerChair(state, theirs, tally);
  return { state, overridden: tally.overridden };
};
