import type { DockView, DoorView, FloorTile, Frame, LightView, MapSoundView, MapSprite, RenderedMap, ScreenView, SignView, SiteView } from '@pixeloffice/protocol';
import { CAPSULE_FRAME, isFacePart, itemView, lintelPart, wallFacePart, type Catalog, type ItemView, type Part, type WallPart } from './catalog.ts';
import { defaultAssetUrl } from './characters.ts';
import { fail, ok, type MapError, type Result } from './errors.ts';
import { matchWhen } from './grid.ts';
import { zoneAt, type OfficeLayout } from './office.ts';
import { doorFrames, doorGap, entranceDoor, renderSite } from './render-site.ts';
import { itemLights, siteLights } from './render-lights.ts';
import { renderRoofs } from './render-roofs.ts';
import { renderSign, type SignInput } from './render-sign.ts';
import type { WorldMap } from './world-map.ts';

// URL ассета живёт в characters.ts (подпуть @pixeloffice/core/characters для вьюера); здесь — реэкспорт.
export { defaultAssetUrl };

// Звуки вида предмета на клетке (x, y) в мировых пикселях (спека фонтана 4.2): клетка × ts + at, как у света.
export const itemSounds = (view: ItemView, x: number, y: number, ts: number): MapSoundView[] =>
  view.sounds.map((s) => ({ type: s.type, x: x * ts + s.at[0], y: y * ts + s.at[1] }));

// Отрендеренная карта для hello: сервер — источник правды для того, что рисовать (спека 4.6). sign — вывеска над входом
// (спека вывески 3.4), только при участке; её ошибки — в файле sign.file.
export function renderMap(
  layout: OfficeLayout,
  map: WorldMap,
  catalog: Catalog,
  assetUrl: (path: string) => string = defaultAssetUrl,
  file = 'office.yaml',
  sign?: SignInput,
): Result<RenderedMap> {
  const ts = catalog.tileSize;
  const { width, height } = layout;
  const errors: MapError[] = [];
  const frame = (sheet: string, r: [number, number, number, number]): Frame => ({
    sheet: assetUrl(catalog.sheets[sheet]!),
    x: r[0],
    y: r[1],
    w: r[2],
    h: r[3],
  });
  const sprites: MapSprite[] = [];
  // Часть с anim (спека фонтана 4.1) — ещё и кадры петли: rect, сдвинутый вправо на i × w.
  const put = (p: Part, x: number, y: number) => {
    const [rx, ry, rw, rh] = p.rect;
    const anim = p.anim && { frames: Array.from({ length: p.anim.frames }, (_, i) => frame(p.sheet, [rx + i * rw, ry, rw, rh])), fps: p.anim.fps };
    sprites.push({ frame: frame(p.sheet, p.rect), px: x * ts + p.at[0], py: y * ts + p.at[1], sortY: (y + p.sortY) * ts, ...(anim ? { anim } : {}) });
  };
  const kindAt = (x: number, y: number) => layout.base[y * width + x];
  const auto = catalog.items['wall']!.autotile!;
  const site = layout.site;
  // При участке нижний ряд стен — по autotile.site (спека 4.7): толстая кромка, торцы у проёма и дверь не рисуются.
  const bottomRules = auto.site?.rules ?? [];
  const wallBit = (x: number, y: number): 0 | 1 =>
    x < 0 || y < 0 || x >= width || y >= height ? auto.outside : kindAt(x, y) === 'wall' ? 1 : 0;
  // Значение по зоне клетки (пол, стиль стен): зоны не пересекаются (zone_overlap), у клетки не больше одной зоны.
  // Нет зоны или записи для неё в table — null.
  const byZone = (table: Record<string, string>, x: number, y: number): string | null => {
    const id = zoneAt(layout.zones, x, y)?.id;
    return id !== undefined && Object.hasOwn(table, id) ? table[id]! : null;
  };
  const floorType = (x: number, y: number) => byZone(layout.floor.zones, x, y) ?? layout.floor.default;
  // Лицо смотрит в комнату клетки под стеной и берёт её стиль (спека северных комнат 5.3); нет записи — walls.default.
  const wallStyle = (x: number, y: number) => {
    const name = byZone(layout.walls.zones, x, y) ?? layout.walls.default;
    return name ? catalog.wallStyles[name]! : null;
  };
  // Часть face — кадр стиля; без стиля частей face не бывает (wall_style_missing). Кромки — обычные части, от стиля не зависят.
  const putWall = (p: WallPart, x: number, y: number) => {
    if (!isFacePart(p)) put(p, x, y);
    else {
      const style = wallStyle(x, y + 1);
      if (style) put(wallFacePart(p, style, ts), x, y);
    }
  };

  const floor: FloorTile[] = [];
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      const k = kindAt(x, y);
      if (k !== 'wall') {
        const frames = catalog.floors[floorType(x, y)]!;
        const fr = frames[(x * 7 + y * 13) % frames.length]!;
        floor.push({ x, y, frame: frame(fr.sheet, fr.rect) });
      }
      // При участке door не рисуется только у проёма южного ряда — над ним door_band (спека 4.7); прочие входы как раньше.
      if (k === 'entrance' && !(site && y === height - 1)) for (const p of auto.door) put(p, x, y);
      if (k === 'wall') {
        const rule = (site && y === height - 1 ? bottomRules : auto.rules).find((r) => matchWhen(r.when, (bit, dx, dy) => wallBit(x + dx, y + dy) === bit));
        if (!rule) errors.push({ file, code: 'wall_no_rule', message: 'ни одно правило autotile стены не подходит', at: [x, y] });
        else for (const p of rule.parts) putWall(p, x, y);
      }
    }
  }
  // Экраны предметов (спека экранов 4.1): мировые пиксели, sortY и место оператора по клетке предмета + seat.
  const screens: ScreenView[] = [];
  const loopTurn = new Map<string, number>(); // loop-программа → сколько её экранов уже раздано: спрайты по очереди
  const lights: LightView[] = []; // источники света (спека ночи 3.4): предметы здания, затем участок, фасад и дверь
  const sounds: MapSoundView[] = []; // звуки на месте (спека фонтана 4.2): предметы здания, затем участка
  for (const it of layout.items) {
    const view = itemView(catalog.items[it.item]!, it.facing, it.variant);
    for (const p of view.parts) put(p, it.x, it.y);
    lights.push(...itemLights(view, it.x, it.y, ts, false)); // предметы здания горят по присутствию
    sounds.push(...itemSounds(view, it.x, it.y, ts));
    view.screens.forEach((s, i) => {
      const prog = catalog.screenArt?.programs[s.program];
      let sprite: string | undefined;
      if (prog?.kind === 'loop') {
        const n = loopTurn.get(s.program) ?? 0;
        loopTurn.set(s.program, n + 1);
        sprite = prog.sprites[n % prog.sprites.length]!;
      }
      screens.push({
        id: `${it.uid}#screen${i}`,
        px: it.x * ts + s.rect[0],
        py: it.y * ts + s.rect[1],
        w: s.rect[2],
        h: s.rect[3],
        ...(s.mask ? { mask: s.mask } : {}),
        sortY: (it.y + s.sortY) * ts,
        program: s.program,
        spot: map.spotAt(it.x + s.seat[0], it.y + s.seat[1])?.id ?? null,
        ...(sprite ? { sprite } : {}),
      });
    });
  }
  const doors: DoorView[] = [];
  let siteView: SiteView | undefined;
  let signView: SignView | undefined;
  if (site) {
    const gap = doorGap(layout);
    if (!gap.ok) errors.push({ file, code: 'door_gap', message: gap.message, at: gap.at });
    else {
      siteView = renderSite(layout, catalog, gap.x, frame, put);
      if (sign) {
        const s = renderSign(layout, catalog, gap.x, sign, frame);
        if (!s.ok) errors.push(...s.errors);
        else {
          sprites.push(...s.value.sprites);
          signView = s.value.view;
        }
      }
      doors.push(entranceDoor(layout, catalog, gap.x, frame));
      lights.push(...siteLights(layout, catalog, gap.x));
      for (const it of site.items) {
        const def = catalog.items[it.item]!;
        if (def.layer !== 'ground') sounds.push(...itemSounds(itemView(def, it.facing, it.variant), it.x, it.y, ts));
      }
    }
  }
  // Двери-предметы (спека северных комнат 6.1): кадр — от клетки предмета со сдвигом at, sortY — от его ряда, датчик —
  // клетки от левого верха предмета. В sprites их нет: рисует и анимирует вьюер. Вид звука `door.sound` — в
  // `DoorView.sound`, только если задан. Перемычка (спека крыш 3.2) — неподвижные куски лица стены в sprites: место —
  // от кадра двери (он совпадает с лицом стены, at [0, −ts] — иначе door_geometry), глубина — как у кадра (стоящий в
  // проёме — перед ней, стоящий в ряду выше — за ней), стиль — по зоне клетки под столбцом куска, как у лица стены. Без
  // стиля лиц перемычки нет, как и самих лиц.
  for (const it of layout.items) {
    const d = catalog.items[it.item]!.door;
    if (!d) continue;
    const [dx, dy, w, h] = d.sensor;
    doors.push({ px: it.x * ts + d.at[0], py: it.y * ts + d.at[1], sortY: (it.y + d.sortY) * ts, frames: doorFrames(d, frame), fps: d.fps, holdMs: Math.round(d.hold * 1000), sensor: [it.x + dx, it.y + dy, w, h], ...(d.sound ? { sound: d.sound } : {}) });
    const lintel = d.lintel;
    if (lintel)
      for (const r of lintel.rects) {
        const style = wallStyle(it.x + Math.floor(r[0] / ts), it.y + 1);
        if (!style) continue;
        const p = lintelPart(lintel.face, r, style, ts);
        sprites.push({ frame: frame(p.sheet, p.rect), px: it.x * ts + d.at[0] + r[0], py: it.y * ts + d.at[1] + r[1], sortY: (it.y + d.sortY) * ts });
      }
  }
  // blocked — по всей карте ходьбы: при участке отладочный слой показывает дорогу, блоки участка и зебру.
  const blocked: [number, number][] = [];
  for (let i = 0; i < map.size; i++) {
    const [x, y] = map.cell(i);
    if (map.isBlocked(x, y)) blocked.push([x, y]);
  }
  // Капсулы (спека маршрутов 5.1): кадр рисования — от клетки дока плюс сдвиг капсулы, sortY — низ кадра.
  const docks: DockView[] = map.portals.docks.map((d) => {
    const def = catalog.items[d.item.id]!.dock!;
    return {
      spot: d.spotId,
      point: d.point,
      px: d.item.x * ts + d.at[0],
      py: d.item.y * ts + d.at[1],
      sortY: (d.item.y + CAPSULE_FRAME[1]) * ts,
      windows: def.windows,
      lift: def.lift,
      cells: d.cells,
      plinth: d.plinth,
    };
  });
  // Крыши (спека крыш 4.5) — отдельным списком: вьюер показывает и прячет их, не трогая остальную карту.
  const roofs = renderRoofs(layout, catalog, frame);
  if (errors.length) return fail(errors);
  return ok({
    tileSize: ts,
    width,
    height,
    floor,
    sprites,
    spots: map.spots.map((s) => ({ id: s.id, x: s.x, y: s.y, facing: s.facing, pose: s.pose, zoneId: s.zoneId, tags: s.tags })),
    blocked,
    entrance: map.entrance(),
    hidden: map.hiddenCells,
    docks,
    doors,
    ...(siteView ? { site: siteView } : {}),
    ...(signView ? { sign: signView } : {}), // нет вывески — hello как раньше
    ...(screens.length && catalog.screenArt ? { screens, screenArt: catalog.screenArt } : {}), // офис без экранов — hello как раньше
    ...(lights.length ? { lights } : {}), // офис без источников света — hello как раньше
    ...(sounds.length ? { sounds } : {}), // карта без звуков на месте — hello как раньше
    ...(roofs.length ? { roofs } : {}), // офис без крыш — hello как раньше
  });
}
