#!/usr/bin/env python3
"""Dump data from a 4KBrowser installation.

This handles the directly readable parts:

* UTF-16LE null-terminated string tables under Database directories.
* Plain image assets such as BMP/JPG/GIF/PNG files.
* A manifest describing XDF text volumes, FTS indexes, and image CD presence.

It can also decode body-text blocks from Text000*.xdf with --dump-body. That
path follows the original client:

* 4KServer/Index/level1.idx maps logical text groups to physical TextNNNN.xdf.
* 4KServer/Index/level2.idx maps logical IDs to XDF offsets and sizes.
* 4kText.exe contains the IDEA schedule used to decrypt each block payload.
* Data/4kqs.frq or 4KServer/Index/4kqs.frq contains one Huffman frequency table
  per logical group.

With --body-layout it also writes the text layout records used by the original
renderer: row, column, character count, and style flags.
"""

from __future__ import annotations

import argparse
import html
import hashlib
import json
import re
import struct
import shutil
from contextlib import nullcontext
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable


IMAGE_EXTS = {
    ".bmp",
    ".gif",
    ".ico",
    ".jfif",
    ".jgp",
    ".jpeg",
    ".jpg",
    ".png",
    ".webp",
}

KNOWN_DB_INDEX_RECORD_SIZES = {
    "n4KDic.Idx": 16,
    "nABook.Idx": 16,
    "nAuthor.Idx": 32,
    "nBook.Idx": 44,
    "nBu.Idx": 12,
    "nDynasty.Idx": 12,
    "nInRoll.Idx": 24,
    "nLei.Idx": 16,
    "nRollDB.Idx": 32,
    "nShu.Idx": 16,
    "volinroll.idx": 40,
}

COMMON_RECORD_SIZES = (8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 64)

CLIENT_TEXT_IDEA_SCHEDULE = bytes.fromhex(
    "f2 5f 56 d2 eb 94 8b 5e eb a5 c1 0b c9 8e 27 e3 "
    "c3 d7 8b bb c2 20 c2 68 e0 fe 4b 30 27 05 2f 7f "
    "9b 26 2b db 7b 3c 11 1a c5 e1 6c d3 f8 86 63 12 "
    "1d c3 e0 50 08 eb f1 a2 dc e4 6e 30 cd 35 dc e9 "
    "2a 61 91 75 9a 74 19 6b a6 db d9 c5 77 78 f2 91 "
    "e1 f6 68 e9 a1 5a 84 24 e3 db 76 4e 08 f4 3f d6 "
    "a5 b7 ce 87 cf 64 69 b9"
)


@dataclass
class TextTableSummary:
    source: str
    output: str
    rows_written: int
    truncated: bool


@dataclass
class ImageSummary:
    source: str
    output: str | None
    size: int
    sha256: str
    kind: str


@dataclass
class BodyBlockSummary:
    logical_id: int
    group: int
    physical_text_no: int
    xdf_offset: int
    stored_size: int
    decoded_size: int
    text_fragment_count: int
    text_char_count: int
    layout_record_count: int
    embedded_images: int
    decoded_output: str | None


@dataclass
class DecodedChunk:
    chunk_type: int
    chunk_offset: int
    payload_offset: int
    payload_size: int


def rel_to(root: Path, path: Path) -> str:
    return path.relative_to(root).as_posix()


def safe_output_name(rel_path: str, suffix: str) -> str:
    parts = Path(rel_path).parts
    stem = "__".join(parts)
    if "." in stem:
        stem = stem.rsplit(".", 1)[0]
    return f"{stem}{suffix}"


def tsv_escape(value: str) -> str:
    return (
        value.replace("\\", "\\\\")
        .replace("\0", "\\0")
        .replace("\t", "\\t")
        .replace("\r", "\\r")
        .replace("\n", "\\n")
    )


def resolve_skqs_map_path(path: Path) -> Path:
    path = path.expanduser().resolve()
    if path.suffix.lower() not in {".html", ".htm"}:
        return path

    html = path.read_text(encoding="utf-8", errors="replace")
    match = re.search(r"""src=["']([^"']*skqs\.json)["']""", html, re.IGNORECASE)
    if match:
        candidate = (path.parent / match.group(1)).resolve()
        if candidate.exists():
            return candidate

    candidate = path.with_name("skqs.json")
    if candidate.exists():
        return candidate
    return path


def load_skqs_character_map(path: Path | None) -> dict[str, str]:
    if path is None:
        return {}

    map_path = resolve_skqs_map_path(path)
    data = map_path.read_text(encoding="utf-8")
    data = data.strip()
    data = re.sub(r"^var\s+data\s*=\s*", "", data)
    data = re.sub(r";\s*$", "", data)
    loaded = json.loads(data)
    if not isinstance(loaded, dict):
        raise ValueError(f"SKQS map did not contain an object: {map_path}")
    return {str(key): str(value) for key, value in loaded.items()}


def normalize_skqs_text(text: str, character_map: dict[str, str]) -> tuple[str, int]:
    if not character_map:
        return text, 0

    output: list[str] = []
    replacement_count = 0
    for char in text:
        replacement = character_map.get(char)
        if replacement is None:
            codepoint = ord(char)
            # Some decoded body text stores the first SKQS private-use page as
            # U+1000..U+10FF; the public comparison table indexes it at
            # U+E000..U+E0FF. Do not apply this to broader symbol ranges such
            # as U+25CB, which are real text in entries like "一○東".
            if 0x1000 <= codepoint <= 0x10FF:
                replacement = character_map.get(chr(codepoint + 0xD000))

        if replacement is None:
            output.append(char)
        else:
            output.append(replacement)
            replacement_count += 1

    return "".join(output), replacement_count


def normalize_skqs_text_cells(text: str, character_map: dict[str, str]) -> tuple[list[str], int]:
    if not character_map:
        return list(text), 0

    cells: list[str] = []
    replacement_count = 0
    for char in text:
        replacement = character_map.get(char)
        if replacement is None:
            codepoint = ord(char)
            if 0x1000 <= codepoint <= 0x10FF:
                replacement = character_map.get(chr(codepoint + 0xD000))

        if replacement is None:
            cells.append(char)
        else:
            cells.append(replacement)
            replacement_count += 1

    return cells, replacement_count


def iter_utf16le_null_strings(path: Path) -> Iterable[tuple[int, int, str]]:
    data = path.read_bytes()
    if len(data) % 2:
        data = data[:-1]

    index = 0
    start: int | None = None
    buf = bytearray()

    for offset in range(0, len(data), 2):
        code_unit = data[offset] | (data[offset + 1] << 8)
        if code_unit == 0:
            if buf:
                text = bytes(buf).decode("utf-16le", errors="replace")
                yield index, start if start is not None else offset, text
                index += 1
                start = None
                buf.clear()
            continue

        if start is None:
            start = offset
        buf.extend(data[offset : offset + 2])

    if buf:
        text = bytes(buf).decode("utf-16le", errors="replace")
        yield index, start if start is not None else len(data), text


def dump_text_tables(root: Path, out_dir: Path, limit_rows: int | None) -> list[TextTableSummary]:
    summaries: list[TextTableSummary] = []
    text_out = out_dir / "text_tables"
    text_out.mkdir(parents=True, exist_ok=True)

    database_dirs = [root / "Database", root / "4KServer" / "Database"]
    dat_files: list[Path] = []
    for database_dir in database_dirs:
        if database_dir.is_dir():
            dat_files.extend(sorted(database_dir.glob("*.Dat")))
            dat_files.extend(sorted(database_dir.glob("*.dat")))

    for dat_path in sorted(set(dat_files)):
        rel = rel_to(root, dat_path)
        out_path = text_out / safe_output_name(rel, ".tsv")
        rows_written = 0
        truncated = False

        with out_path.open("w", encoding="utf-8", newline="") as handle:
            handle.write("row\tbyte_offset\ttext\n")
            for row, byte_offset, text in iter_utf16le_null_strings(dat_path):
                if limit_rows is not None and rows_written >= limit_rows:
                    truncated = True
                    break
                handle.write(f"{row}\t{byte_offset}\t{tsv_escape(text)}\n")
                rows_written += 1

        summaries.append(
            TextTableSummary(
                source=rel,
                output=rel_to(out_dir, out_path),
                rows_written=rows_written,
                truncated=truncated,
            )
        )

    return summaries


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def sniff_image_kind(path: Path) -> str:
    header = path.read_bytes()[:16]
    if header.startswith(b"\xff\xd8\xff"):
        return "jpeg"
    if header.startswith((b"GIF87a", b"GIF89a")):
        return "gif"
    if header.startswith(b"BM"):
        return "bmp"
    if header.startswith(b"\x89PNG\r\n\x1a\n"):
        return "png"
    if header.startswith(b"RIFF") and header[8:12] == b"WEBP":
        return "webp"
    if header.startswith(b"\x00\x00\x01\x00"):
        return "ico"
    return "unknown"


def idea_mul(left: int, right: int) -> int:
    left = 0x10000 if (left & 0xFFFF) == 0 else left & 0xFFFF
    right = 0x10000 if (right & 0xFFFF) == 0 else right & 0xFFFF
    product = left * right
    result = (product & 0xFFFF) - (product >> 16)
    if result < 0:
        result += 0x10001
    return result & 0xFFFF


def idea_mul_inverse(value: int) -> int:
    value &= 0xFFFF
    if value <= 1:
        return value

    old_t, t = 0, 1
    old_r, r = 0x10001, value
    while r:
        quotient = old_r // r
        old_t, t = t, old_t - quotient * t
        old_r, r = r, old_r - quotient * r
    if old_t < 0:
        old_t += 0x10001
    return old_t & 0xFFFF


def idea_add_inverse(value: int) -> int:
    return (-value) & 0xFFFF


def make_idea_decrypt_schedule(encrypt_schedule: bytes) -> list[int]:
    keys = list(struct.unpack("<52H", encrypt_schedule[:104]))
    out = [0] * 52

    for round_index in range(7):
        out[42 - 6 * round_index] = idea_mul_inverse(keys[6 + 6 * round_index])
        out[43 - 6 * round_index] = idea_add_inverse(keys[8 + 6 * round_index])
        out[44 - 6 * round_index] = idea_add_inverse(keys[7 + 6 * round_index])
        out[45 - 6 * round_index] = idea_mul_inverse(keys[9 + 6 * round_index])
        out[46 - 6 * round_index] = keys[4 + 6 * round_index]
        out[47 - 6 * round_index] = keys[5 + 6 * round_index]

    out[48] = idea_mul_inverse(keys[0])
    out[49] = idea_add_inverse(keys[1])
    out[50] = idea_add_inverse(keys[2])
    out[51] = idea_mul_inverse(keys[3])
    out[0] = idea_mul_inverse(keys[48])
    out[1] = idea_add_inverse(keys[49])
    out[2] = idea_add_inverse(keys[50])
    out[3] = idea_mul_inverse(keys[51])
    for round_index in range(8):
        out[46 - 6 * round_index] = keys[4 + 6 * round_index]
        out[47 - 6 * round_index] = keys[5 + 6 * round_index]

    return out


def read_client_idea_schedule(root: Path) -> bytes:
    client = root / "4kText.exe"
    if client.exists():
        data = client.read_bytes()
        raw_offset = 0x12A268
        if len(data) >= raw_offset + 104:
            return data[raw_offset : raw_offset + 104]
    return CLIENT_TEXT_IDEA_SCHEDULE


def idea_transform_blocks(data: bytes, schedule: list[int]) -> bytes:
    usable_len = len(data) - (len(data) % 8)
    output = bytearray(data[:usable_len])

    for offset in range(0, usable_len, 8):
        x1, x2, x3, x4 = struct.unpack_from("<4H", data, offset)
        key_pos = 0
        for _ in range(8):
            x1 = idea_mul(x1, schedule[key_pos])
            x2 = (x2 + schedule[key_pos + 1]) & 0xFFFF
            x3 = (x3 + schedule[key_pos + 2]) & 0xFFFF
            x4 = idea_mul(x4, schedule[key_pos + 3])

            t0 = idea_mul(x1 ^ x3, schedule[key_pos + 4])
            t1 = idea_mul(((x2 ^ x4) + t0) & 0xFFFF, schedule[key_pos + 5])
            t0 = (t0 + t1) & 0xFFFF

            x1 ^= t1
            x4 ^= t0
            x2, x3 = x3 ^ t1, x2 ^ t0
            key_pos += 6

        y1 = idea_mul(x1, schedule[48])
        y2 = (x3 + schedule[49]) & 0xFFFF
        y3 = (x2 + schedule[50]) & 0xFFFF
        y4 = idea_mul(x4, schedule[51])
        struct.pack_into("<4H", output, offset, y1, y2, y3, y4)

    if usable_len != len(data):
        output.extend(data[usable_len:])
    return bytes(output)


def load_frequency_tables(root: Path) -> bytes:
    candidates = [
        root / "4KServer" / "Index" / "4kqs.frq",
        root / "Data" / "4kqs.frq",
    ]
    for candidate in candidates:
        if candidate.exists():
            return candidate.read_bytes()
    raise FileNotFoundError("Could not find 4kqs.frq frequency table.")


def build_huffman_tree(values: tuple[int, ...]) -> tuple[list[int], list[int], int]:
    weights = [0.0] * 512
    active = [0] * 512
    left = [-1] * 512
    right = [-1] * 512

    for index, value in enumerate(values):
        weights[index] = float(value)
        active[index] = 1

    count = 256
    for _ in range(255):
        first_weight = 100000.0
        second_weight = 100000.0
        first_index = 0
        second_index = 0

        for index in range(count):
            if not active[index]:
                continue
            weight = weights[index]
            if second_weight < weight:
                continue
            if weight <= 0:
                continue
            if weight <= first_weight:
                second_weight = first_weight
                second_index = first_index
                first_weight = weight
                first_index = index
            else:
                second_weight = weight
                second_index = index

        active[first_index] = 0
        active[second_index] = 0
        active[count] = 1
        weights[count] = first_weight + second_weight
        left[count] = first_index
        right[count] = second_index
        count += 1

    return left, right, count - 1


def decode_huffman(
    bitstream: bytes,
    output_size: int,
    tree: tuple[list[int], list[int], int],
) -> bytes:
    left, right, root_index = tree
    output = bytearray()
    bit_position = 0

    for _ in range(output_size):
        node = root_index
        while node > 0xFF:
            byte_index = bit_position >> 3
            if byte_index >= len(bitstream):
                raise ValueError("Huffman bitstream ended before output was complete.")
            bit = bitstream[byte_index] & (1 << (bit_position & 7))
            bit_position += 1
            node = right[node] if bit else left[node]
            if node < 0:
                raise ValueError("Invalid Huffman tree traversal.")
        output.append(node & 0xFF)

    return bytes(output)


def decode_xdf_block(raw_block: bytes, group: int, idea_schedule: list[int], frq_data: bytes, tree_cache: dict[int, tuple[list[int], list[int], int]]) -> bytes:
    if len(raw_block) < 4:
        raise ValueError("XDF block is too short.")

    output_size = struct.unpack_from("<I", raw_block, 0)[0]
    encrypted_payload = raw_block[4:]
    decrypted_payload = idea_transform_blocks(encrypted_payload, idea_schedule)

    if group not in tree_cache:
        table_offset = group * 512
        if table_offset + 512 > len(frq_data):
            raise ValueError(f"Frequency table missing group {group}.")
        values = struct.unpack_from("<256h", frq_data, table_offset)
        tree_cache[group] = build_huffman_tree(values)

    return decode_huffman(decrypted_payload, output_size, tree_cache[group])


def iter_decoded_chunks(data: bytes) -> Iterable[DecodedChunk]:
    """Yield top-level chunks from a decoded body block.

    The client parser starts at byte 0x18 and reads each chunk as
    uint32 type + uint32 payload size + payload.
    """
    if len(data) < 24:
        return

    offset = 24
    while offset + 8 <= len(data):
        chunk_type, payload_size = struct.unpack_from("<II", data, offset)
        payload_offset = offset + 8
        payload_end = payload_offset + payload_size
        if payload_end > len(data):
            break
        yield DecodedChunk(
            chunk_type=chunk_type,
            chunk_offset=offset,
            payload_offset=payload_offset,
            payload_size=payload_size,
        )
        offset = payload_end


def body_block_header(data: bytes) -> tuple[int, int, int, int, int, int] | None:
    if len(data) < 24:
        return None
    return struct.unpack_from("<6I", data, 0)


def layout_render_flag(style: int) -> int:
    low = style & 0x0F
    if low == 1:
        if style & 0x10:
            return 4
        if style & 0x20:
            return 8
    if low == 3:
        return 1
    return 0


def layout_lane_label(style: int) -> str:
    low = style & 0x0F
    if low == 3:
        return "main"
    if low == 1:
        if style & 0x10:
            return "upper"
        if style & 0x20:
            return "lower"
        return "small"
    return "other"


def layout_lane_order(style: int) -> int:
    lane = layout_lane_label(style)
    if lane == "main":
        return 0
    if lane == "upper":
        return 1
    if lane == "lower":
        return 2
    return 3


def parse_body_layout_records(data: bytes) -> list[dict[str, object]]:
    header = body_block_header(data)
    if header is None:
        return []

    _, packed_metric, block_flags, block_width, block_height, _ = header
    metric_lo = packed_metric & 0xFFFF
    metric_hi = packed_metric >> 16
    records: list[dict[str, object]] = []

    for chunk in iter_decoded_chunks(data):
        if chunk.chunk_type not in (1, 6):
            continue

        position = chunk.payload_offset
        payload_end = chunk.payload_offset + chunk.payload_size
        record_index = 0
        while position + 16 <= payload_end:
            row, column, char_count, style = struct.unpack_from("<IIII", data, position)
            text_start = position + 16

            if chunk.chunk_type == 1:
                text_end = text_start + char_count * 2
                if text_end > payload_end:
                    break
                text = data[text_start:text_end].decode("utf-16le", errors="replace")
            else:
                text_end = text_start + char_count * 4
                if text_end > payload_end:
                    break
                chars: list[str] = []
                for entry_offset in range(text_start, text_end, 4):
                    codepoint = struct.unpack_from("<H", data, entry_offset + 2)[0]
                    chars.append(chr(codepoint))
                text = "".join(chars)

            records.append(
                {
                    "block_payload_size": header[0],
                    "block_flags": block_flags,
                    "block_width": block_width,
                    "block_height": block_height,
                    "metric_lo": metric_lo,
                    "metric_hi": metric_hi,
                    "chunk_type": chunk.chunk_type,
                    "chunk_offset": chunk.chunk_offset,
                    "payload_offset": chunk.payload_offset,
                    "record_index": record_index,
                    "row": row,
                    "column": column,
                    "char_count": char_count,
                    "style": style,
                    "style_low": style & 0x0F,
                    "style_extra_flags": style & ~0x0F,
                    "render_flag": layout_render_flag(style),
                    "lane": layout_lane_label(style),
                    "text": text,
                }
            )
            record_index += 1
            position = text_end

    return records


def write_body_layout_rows(
    handle,
    logical_id: int,
    group: int,
    physical_text_no: int,
    records: list[dict[str, object]],
) -> None:
    if not records:
        return

    first = records[0]
    handle.write(
        f"\n[{logical_id:08x}] group={group} physical_text_no={physical_text_no} "
        f"page={first['block_width']}x{first['block_height']} "
        f"metric={first['metric_lo']}/{first['metric_hi']} records={len(records)}\n"
    )

    rows: dict[int, list[dict[str, object]]] = {}
    for record in records:
        rows.setdefault(int(record["row"]), []).append(record)

    for row in sorted(rows):
        parts: list[str] = []
        for record in sorted(
            rows[row],
            key=lambda item: (
                int(item["column"]),
                layout_lane_order(int(item["style"])),
                int(item["record_index"]),
            ),
        ):
            text = str(record["text"]).replace("\t", " ").replace("\r", "\\r").replace("\n", "\\n")
            parts.append(
                f"{int(record['column']):02d}:{record['lane']}:{text}"
            )
        handle.write(f"row {row:03d}\t{' | '.join(parts)}\n")


def html_attr(value: object) -> str:
    return html.escape(str(value), quote=True)


def display_char_count(text: str) -> int:
    return max(1, len(text))


def write_body_layout_html_header(handle) -> None:
    handle.write(
        """<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>4KBrowser Body Layout</title>
<style>
:root {
  color-scheme: light;
  --ink: #1f2520;
  --muted: #6d746c;
  --line: #cfc8b7;
  --paper: #fffdf5;
  --desk: #e9e4d7;
  --accent: #7b1f22;
}
* { box-sizing: border-box; }
body {
  margin: 0;
  background: var(--desk);
  color: var(--ink);
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
.toolbar {
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  gap: 10px;
  align-items: center;
  padding: 10px 14px;
  border-bottom: 1px solid var(--line);
  background: rgba(250, 248, 240, 0.96);
  backdrop-filter: blur(8px);
}
.toolbar strong { font-size: 14px; letter-spacing: 0; white-space: nowrap; }
.toolbar select, .toolbar button {
  height: 30px;
  border: 1px solid #b8af9d;
  border-radius: 4px;
  background: #fffdf8;
  color: var(--ink);
  font-size: 13px;
}
.toolbar button { width: 34px; cursor: pointer; }
.toolbar .count { margin-left: auto; color: var(--muted); font-size: 13px; white-space: nowrap; }
.pages {
  width: min(960px, 100%);
  margin: 0 auto;
  padding: 18px 14px 42px;
}
.page-shell {
  margin: 0 0 22px;
}
.page-meta {
  display: flex;
  gap: 10px;
  align-items: baseline;
  padding: 0 2px 6px;
  color: var(--muted);
  font-size: 12px;
}
.page-meta a {
  color: var(--accent);
  font-weight: 650;
  text-decoration: none;
}
.page-scroll {
  overflow-x: auto;
  padding-bottom: 4px;
}
.page {
  position: relative;
  display: grid;
  grid-template-columns: repeat(var(--cols), minmax(0, 1fr));
  grid-template-rows: repeat(var(--rows), minmax(0, 1fr));
  width: min(860px, calc(100vw - 34px));
  min-width: 700px;
  aspect-ratio: var(--page-w) / var(--page-h);
  background: var(--paper);
  border: 1px solid #bfb6a3;
  box-shadow: 0 1px 2px rgba(50, 42, 30, 0.12);
  padding: 28px 34px;
  font-family: FSung-1, FSung-2, FSung-3, FSung-x, FSung-m, FSung-F,
    "Songti SC", "STSong", "SimSun-ExtB", "HanaMinB", "Noto Serif CJK TC",
    "Noto Serif CJK SC", serif;
}
.page::before {
  content: "";
  position: absolute;
  inset: 14px 18px;
  border: 1px solid rgba(124, 111, 89, 0.20);
  pointer-events: none;
}
.page::after {
  content: "";
  position: absolute;
  inset: 28px 34px;
  background-image: repeating-linear-gradient(
    to left,
    transparent 0,
    transparent calc((100% / var(--major-cols)) - 1px),
    rgba(78, 70, 54, 0.28) calc((100% / var(--major-cols)) - 1px),
    rgba(78, 70, 54, 0.28) calc(100% / var(--major-cols))
  );
  pointer-events: none;
  z-index: 1;
}
.seg {
  min-width: 0;
  min-height: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  align-self: stretch;
  justify-self: center;
  overflow: hidden;
  writing-mode: horizontal-tb;
  white-space: nowrap;
  line-height: 1;
  letter-spacing: 0;
  font-variant-ligatures: none;
  text-rendering: geometricPrecision;
  user-select: text;
}
.lane-main {
  z-index: 2;
  font-size: calc(clamp(25px, 3.6vw, 38px) * var(--fit));
  font-weight: 500;
}
.lane-upper,
.lane-lower {
  z-index: 3;
  color: #2f3930;
  font-size: calc(clamp(13px, 1.8vw, 19px) * var(--fit));
  font-weight: 450;
}
.lane-upper { justify-self: center; }
.lane-lower { justify-self: center; }
.empty-page {
  display: grid;
  place-items: center;
  min-height: 220px;
  color: var(--muted);
  background: var(--paper);
  border: 1px solid #bfb6a3;
  font-size: 13px;
}
@media (max-width: 760px) {
  .toolbar { gap: 6px; padding: 8px; }
  .toolbar strong { display: none; }
  .toolbar .count { display: none; }
  .pages { padding: 12px 8px 28px; }
  .page { min-width: 700px; }
}
</style>
</head>
<body>
<div class="toolbar">
  <strong>4KBrowser Layout</strong>
  <button type="button" id="prevPage" title="Previous page">&#8593;</button>
  <button type="button" id="nextPage" title="Next page">&#8595;</button>
  <select id="pageJump" aria-label="Page jump"></select>
  <span class="count" id="pageCount"></span>
</div>
<main class="pages" id="pages">
"""
    )


def write_body_layout_html_page(
    handle,
    logical_id: int,
    group: int,
    physical_text_no: int,
    records: list[dict[str, object]],
    embedded_image_count: int,
) -> None:
    logical = f"{logical_id:08x}"
    handle.write(
        f'<section class="page-shell" id="page-{logical}" data-logical="{logical}">\n'
        f'<div class="page-meta"><a href="#page-{logical}">{logical}</a>'
        f'<span>group {group}</span><span>Text{physical_text_no:04d}</span>'
        f'<span>{len(records)} records</span><span>{embedded_image_count} images</span></div>\n'
    )

    if not records:
        handle.write('<div class="empty-page">No parsed text layout</div></section>\n')
        return

    first = records[0]
    max_layout_row = max(int(record["row"]) for record in records)
    max_layout_col = max(
        int(record["column"]) + max(1, int(record["char_count"]))
        for record in records
    )
    grid_cols = max(1, (max_layout_row + 1) * 2)
    grid_rows = max(1, max_layout_col)
    page_width = max(1, int(first["block_height"]))
    page_height = max(1, int(first["block_width"]))
    handle.write(
        '<div class="page-scroll">'
        f'<div class="page" style="--page-w:{page_width};--page-h:{page_height};'
        f'--cols:{grid_cols};--rows:{grid_rows};--major-cols:{max_layout_row + 1};">\n'
    )

    for record in records:
        row = int(record["row"])
        column = int(record["column"])
        char_count = max(1, int(record["char_count"]))
        lane = str(record["lane"])
        text = str(record["text"])
        raw_text = str(record.get("raw_text") or "")
        raw_cells = list(raw_text) if raw_text else list(text)
        cell_texts = record.get("cell_texts")
        if not isinstance(cell_texts, list):
            cell_texts = list(text)

        subcolumn = (max_layout_row - row) * 2 + 1
        if lane == "upper":
            grid_column = subcolumn + 1
            column_span = 1
            lane_class = "lane-upper"
        elif lane == "lower":
            grid_column = subcolumn
            column_span = 1
            lane_class = "lane-lower"
        else:
            grid_column = subcolumn
            column_span = 2
            lane_class = "lane-main"

        for char_index, cell_text in enumerate(cell_texts[:char_count]):
            if cell_text == " ":
                continue
            grid_row = column + char_index + 1
            raw_cell = raw_cells[char_index] if char_index < len(raw_cells) else ""
            display_len = display_char_count(cell_text)
            fit = max(0.52, min(1.0, 1 / display_len))
            title_bits = [
                f"vertical column {row}",
                f"position {column + char_index}",
                f"style {record['style']}",
            ]
            if raw_cell and raw_cell != cell_text:
                title_bits.append(f"raw {raw_cell}")
            title = "; ".join(title_bits)

            handle.write(
                f'<span class="seg {lane_class}" '
                f'style="grid-column:{grid_column} / span {column_span};'
                f'grid-row:{grid_row};--fit:{fit:.3f};" '
                f'title="{html_attr(title)}">{html_attr(cell_text)}</span>\n'
            )

    handle.write("</div></div></section>\n")


def write_body_layout_html_footer(handle) -> None:
    handle.write(
        """</main>
<script>
(() => {
  const pages = Array.from(document.querySelectorAll(".page-shell"));
  const jump = document.getElementById("pageJump");
  const count = document.getElementById("pageCount");
  let current = 0;

  for (const [index, page] of pages.entries()) {
    const option = document.createElement("option");
    option.value = page.id;
    option.textContent = `${index + 1}. ${page.dataset.logical}`;
    jump.appendChild(option);
  }

  function update(index) {
    if (!pages.length) return;
    current = Math.max(0, Math.min(index, pages.length - 1));
    jump.selectedIndex = current;
    count.textContent = `${current + 1} / ${pages.length}`;
  }

  function go(index) {
    update(index);
    pages[current].scrollIntoView({ block: "start", behavior: "smooth" });
  }

  jump.addEventListener("change", () => go(jump.selectedIndex));
  document.getElementById("prevPage").addEventListener("click", () => go(current - 1));
  document.getElementById("nextPage").addEventListener("click", () => go(current + 1));

  const observer = new IntersectionObserver(entries => {
    const visible = entries
      .filter(entry => entry.isIntersecting)
      .sort((a, b) => b.intersectionRatio - a.intersectionRatio)[0];
    if (!visible) return;
    const index = pages.indexOf(visible.target);
    if (index >= 0) update(index);
  }, { rootMargin: "-10% 0px -70% 0px", threshold: [0.05, 0.2, 0.5] });

  pages.forEach(page => observer.observe(page));
  update(0);
})();
</script>
</body>
</html>
"""
    )


def is_textish_codepoint(codepoint: int) -> bool:
    if codepoint in (0x09, 0x0A, 0x0D):
        return True
    if 0x20 <= codepoint <= 0x7E:
        return True
    if 0x3000 <= codepoint <= 0x303F:
        return True
    if 0x3400 <= codepoint <= 0x4DBF:
        return True
    if 0x4E00 <= codepoint <= 0x9FFF:
        return True
    if 0xE000 <= codepoint <= 0xF8FF:
        return True
    if 0xF900 <= codepoint <= 0xFAFF:
        return True
    if 0xFE10 <= codepoint <= 0xFE6F:
        return True
    if 0xFF00 <= codepoint <= 0xFFEF:
        return True
    return False


def is_cjkish_codepoint(codepoint: int) -> bool:
    return (
        0x3000 <= codepoint <= 0x303F
        or 0x3400 <= codepoint <= 0x4DBF
        or 0x4E00 <= codepoint <= 0x9FFF
        or 0xE000 <= codepoint <= 0xF8FF
        or 0xF900 <= codepoint <= 0xFAFF
        or 0xFE10 <= codepoint <= 0xFE6F
        or 0xFF00 <= codepoint <= 0xFFEF
    )


def extract_utf16le_text_fragments(
    data: bytes,
    min_chars: int,
    skip_ranges: list[tuple[str, int, int]] | None = None,
) -> list[str]:
    fragments: list[str] = []
    current: list[str] = []
    current_score = 0
    sorted_skip_ranges = sorted(skip_ranges or [], key=lambda item: item[1])
    skip_index = 0

    def flush() -> None:
        nonlocal current, current_score
        if len(current) >= min_chars and current_score >= max(1, min_chars // 2):
            fragments.append("".join(current))
        current = []
        current_score = 0

    for offset in range(0, len(data) - 1, 2):
        while skip_index < len(sorted_skip_ranges) and offset >= sorted_skip_ranges[skip_index][2]:
            skip_index += 1
        if (
            skip_index < len(sorted_skip_ranges)
            and sorted_skip_ranges[skip_index][1] <= offset < sorted_skip_ranges[skip_index][2]
        ):
            flush()
            continue

        codepoint = data[offset] | (data[offset + 1] << 8)
        if is_textish_codepoint(codepoint):
            current.append(chr(codepoint))
            if is_cjkish_codepoint(codepoint):
                current_score += 1
        else:
            flush()

    flush()
    return fragments


def find_embedded_image_ranges(data: bytes) -> list[tuple[str, int, int]]:
    ranges: list[tuple[str, int, int]] = []
    signatures = [
        ("tif", b"II*\x00"),
        ("tif", b"MM\x00*"),
        ("jpg", b"\xff\xd8\xff"),
        ("png", b"\x89PNG\r\n\x1a\n"),
        ("gif", b"GIF87a"),
        ("gif", b"GIF89a"),
        ("bmp", b"BM"),
    ]

    for suffix, signature in signatures:
        start = 0
        while True:
            index = data.find(signature, start)
            if index < 0:
                break
            end = len(data)
            if suffix == "jpg":
                eoi = data.find(b"\xff\xd9", index + 2)
                if eoi >= 0:
                    end = eoi + 2
            elif suffix == "png":
                iend = data.find(b"IEND", index + 8)
                if iend >= 0:
                    end = iend + 8
            elif suffix == "bmp" and index + 6 <= len(data):
                bmp_size = struct.unpack_from("<I", data, index + 2)[0]
                if 0 < bmp_size <= len(data) - index:
                    end = index + bmp_size
            ranges.append((suffix, index, end))
            start = index + len(signature)

    ranges.sort(key=lambda item: item[1])
    filtered: list[tuple[str, int, int]] = []
    covered_until = -1
    for item in ranges:
        _, image_start, image_end = item
        if image_start < covered_until:
            continue
        filtered.append(item)
        covered_until = max(covered_until, image_end)
    return filtered


def text_volume_paths(root: Path) -> dict[int, Path]:
    paths: dict[int, Path] = {}
    for path in sorted((root / "4KServer").glob("[0-9][0-9][0-9]/Text*.xdf")):
        name = path.stem
        if name.lower().startswith("text"):
            try:
                paths[int(name[4:])] = path
            except ValueError:
                continue
    return paths


def dump_images(
    root: Path,
    out_dir: Path,
    mode: str,
    limit_images: int | None,
) -> list[ImageSummary]:
    image_out = out_dir / "images"
    if mode == "copy":
        image_out.mkdir(parents=True, exist_ok=True)

    image_paths = sorted(
        path
        for path in root.rglob("*")
        if path.is_file() and path.suffix.lower() in IMAGE_EXTS
    )
    if limit_images is not None:
        image_paths = image_paths[:limit_images]

    summaries: list[ImageSummary] = []
    manifest_path = out_dir / "images_manifest.tsv"
    with manifest_path.open("w", encoding="utf-8", newline="") as handle:
        handle.write("source\toutput\tsize\tsha256\tkind\n")
        for image_path in image_paths:
            rel = rel_to(root, image_path)
            output_rel: str | None = None
            if mode == "copy":
                target = image_out / rel
                target.parent.mkdir(parents=True, exist_ok=True)
                shutil.copy2(image_path, target)
                output_rel = rel_to(out_dir, target)

            size = image_path.stat().st_size
            digest = sha256_file(image_path)
            kind = sniff_image_kind(image_path)
            handle.write(
                f"{rel}\t{output_rel or ''}\t{size}\t{digest}\t{kind}\n"
            )
            summaries.append(
                ImageSummary(
                    source=rel,
                    output=output_rel,
                    size=size,
                    sha256=digest,
                    kind=kind,
                )
            )

    return summaries


def dump_body_blocks(
    root: Path,
    out_dir: Path,
    limit_blocks: int | None,
    start_logical_id: int | None,
    end_logical_id: int | None,
    write_decoded_blocks: bool,
    write_layout: bool,
    write_html: bool,
    body_image_mode: str,
    min_text_chars: int,
    skqs_map_path: Path | None,
) -> dict[str, object]:
    body_out = out_dir / "body"
    body_out.mkdir(parents=True, exist_ok=True)
    decoded_out = body_out / "decoded_blocks"
    embedded_image_out = body_out / "embedded_images"
    if write_decoded_blocks:
        decoded_out.mkdir(parents=True, exist_ok=True)
    if body_image_mode == "extract":
        embedded_image_out.mkdir(parents=True, exist_ok=True)

    level1_path = root / "4KServer" / "Index" / "level1.idx"
    level2_path = root / "4KServer" / "Index" / "level2.idx"
    if not level1_path.exists() or not level2_path.exists():
        raise FileNotFoundError("Could not find 4KServer/Index/level1.idx and level2.idx.")

    level1 = level1_path.read_bytes()
    frq_data = load_frequency_tables(root)
    idea_schedule = make_idea_decrypt_schedule(read_client_idea_schedule(root))
    skqs_character_map = load_skqs_character_map(skqs_map_path)
    resolved_skqs_map_path = resolve_skqs_map_path(skqs_map_path) if skqs_map_path else None
    volumes = text_volume_paths(root)
    tree_cache: dict[int, tuple[list[int], list[int], int]] = {}
    xdf_handles: dict[int, object] = {}

    blocks_tsv = body_out / "body_blocks.tsv"
    text_tsv = body_out / "body_text_fragments.tsv"
    text_txt = body_out / "body_text.txt"
    images_tsv = body_out / "embedded_images_manifest.tsv"
    layout_tsv = body_out / "body_layout_records.tsv"
    layout_rows_txt = body_out / "body_layout_rows.txt"
    layout_html = body_out / "body_layout.html"

    decoded_count = 0
    error_count = 0
    text_block_count = 0
    text_fragment_count = 0
    text_char_count = 0
    layout_record_count = 0
    html_page_count = 0
    skqs_text_replacement_count = 0
    skqs_layout_replacement_count = 0
    embedded_image_count = 0
    summaries: list[BodyBlockSummary] = []

    def get_xdf_handle(physical_text_no: int):
        if physical_text_no not in xdf_handles:
            if physical_text_no not in volumes:
                raise FileNotFoundError(f"Missing Text{physical_text_no:04d}.xdf")
            xdf_handles[physical_text_no] = volumes[physical_text_no].open("rb")
        return xdf_handles[physical_text_no]

    try:
        with (
            level2_path.open("rb") as level2,
            blocks_tsv.open("w", encoding="utf-8", newline="") as blocks_handle,
            text_tsv.open("w", encoding="utf-8", newline="") as text_handle,
            text_txt.open("w", encoding="utf-8") as plain_text_handle,
            images_tsv.open("w", encoding="utf-8", newline="") as images_handle,
            (
                layout_tsv.open("w", encoding="utf-8", newline="")
                if write_layout
                else nullcontext(None)
            ) as layout_handle,
            (
                layout_rows_txt.open("w", encoding="utf-8")
                if write_layout
                else nullcontext(None)
            ) as layout_rows_handle,
            (
                layout_html.open("w", encoding="utf-8")
                if write_html
                else nullcontext(None)
            ) as html_handle,
        ):
            blocks_handle.write(
                "logical_id\tgroup\tphysical_text_no\txdf_offset\tstored_size\t"
                "decoded_size\ttext_fragments\ttext_chars\tlayout_records\tembedded_images\t"
                "decoded_output\terror\n"
            )
            text_handle.write(
                "logical_id\tgroup\tphysical_text_no\txdf_offset\tstored_size\t"
                "decoded_size\ttext\n"
            )
            images_handle.write(
                "logical_id\tgroup\tphysical_text_no\tembedded_offset\tlength\t"
                "kind\tsha256\toutput\n"
            )
            if layout_handle is not None:
                layout_handle.write(
                    "logical_id\tgroup\tphysical_text_no\txdf_offset\tstored_size\t"
                    "decoded_size\tblock_payload_size\tblock_flags\tblock_width\t"
                    "block_height\tmetric_lo\tmetric_hi\tchunk_type\tchunk_offset\t"
                    "payload_offset\trecord_index\trow\tcolumn\tchar_count\tstyle\t"
                    "style_low\tstyle_extra_flags\trender_flag\tlane\ttext\traw_text\n"
                )
            if html_handle is not None:
                write_body_layout_html_header(html_handle)

            group_count = len(level1) // 12
            stop = False
            for group in range(group_count):
                l1_offset, l1_size, l1_flags = struct.unpack_from("<iII", level1, group * 12)
                if l1_offset < 0 or l1_size <= 0:
                    continue

                physical_text_no = l1_flags >> 16
                level2.seek(l1_offset)
                chunk = level2.read(l1_size)
                for record_offset in range(0, len(chunk), 20):
                    logical_id, xdf_offset, stored_size, _, _ = struct.unpack_from(
                        "<IIIII", chunk, record_offset
                    )
                    if start_logical_id is not None and logical_id < start_logical_id:
                        continue
                    if end_logical_id is not None and logical_id > end_logical_id:
                        stop = True
                        break
                    if limit_blocks is not None and decoded_count >= limit_blocks:
                        stop = True
                        break

                    decoded_output_rel: str | None = None
                    error = ""
                    decoded = b""
                    fragments: list[str] = []
                    layout_records: list[dict[str, object]] = []
                    embedded_ranges: list[tuple[str, int, int]] = []

                    try:
                        xdf = get_xdf_handle(physical_text_no)
                        xdf.seek(xdf_offset)
                        raw_block = xdf.read(stored_size)
                        if len(raw_block) != stored_size:
                            raise ValueError("Short read from XDF volume.")

                        decoded = decode_xdf_block(
                            raw_block,
                            group,
                            idea_schedule,
                            frq_data,
                            tree_cache,
                        )
                        embedded_ranges = find_embedded_image_ranges(decoded)
                        fragments = extract_utf16le_text_fragments(
                            decoded,
                            min_text_chars,
                            embedded_ranges,
                        )
                        if skqs_character_map:
                            normalized_fragments: list[str] = []
                            for fragment in fragments:
                                normalized_fragment, replacement_count = normalize_skqs_text(
                                    fragment,
                                    skqs_character_map,
                                )
                                skqs_text_replacement_count += replacement_count
                                normalized_fragments.append(normalized_fragment)
                            fragments = normalized_fragments

                        if write_layout or write_html:
                            layout_records = parse_body_layout_records(decoded)
                            if skqs_character_map:
                                for record in layout_records:
                                    raw_text = str(record["text"])
                                    normalized_cells, replacement_count = normalize_skqs_text_cells(
                                        raw_text,
                                        skqs_character_map,
                                    )
                                    skqs_layout_replacement_count += replacement_count
                                    record["cell_texts"] = normalized_cells
                                    record["text"] = "".join(normalized_cells)
                                    record["raw_text"] = raw_text if replacement_count else ""
                            else:
                                for record in layout_records:
                                    record["cell_texts"] = list(str(record["text"]))
                                    record["raw_text"] = ""
                            layout_record_count += len(layout_records)
                            if layout_handle is not None:
                                for record in layout_records:
                                    layout_handle.write(
                                        f"{logical_id:08x}\t{group}\t{physical_text_no}\t"
                                        f"{xdf_offset}\t{stored_size}\t{len(decoded)}\t"
                                        f"{record['block_payload_size']}\t{record['block_flags']}\t"
                                        f"{record['block_width']}\t{record['block_height']}\t"
                                        f"{record['metric_lo']}\t{record['metric_hi']}\t"
                                        f"{record['chunk_type']}\t{record['chunk_offset']}\t"
                                        f"{record['payload_offset']}\t{record['record_index']}\t"
                                        f"{record['row']}\t{record['column']}\t"
                                        f"{record['char_count']}\t{record['style']}\t"
                                        f"{record['style_low']}\t{record['style_extra_flags']}\t"
                                        f"{record['render_flag']}\t{record['lane']}\t"
                                        f"{tsv_escape(str(record['text']))}\t"
                                        f"{tsv_escape(str(record['raw_text']))}\n"
                                    )
                            if layout_rows_handle is not None:
                                write_body_layout_rows(
                                    layout_rows_handle,
                                    logical_id,
                                    group,
                                    physical_text_no,
                                    layout_records,
                                )
                            if html_handle is not None:
                                write_body_layout_html_page(
                                    html_handle,
                                    logical_id,
                                    group,
                                    physical_text_no,
                                    layout_records,
                                    len(embedded_ranges),
                                )
                                html_page_count += 1

                        if write_decoded_blocks:
                            decoded_path = decoded_out / f"{logical_id:08x}.bin"
                            decoded_path.write_bytes(decoded)
                            decoded_output_rel = rel_to(out_dir, decoded_path)

                        for image_index, (suffix, image_start, image_end) in enumerate(embedded_ranges):
                            payload = decoded[image_start:image_end]
                            digest = hashlib.sha256(payload).hexdigest()
                            image_output_rel = ""
                            if body_image_mode == "extract":
                                image_path = (
                                    embedded_image_out
                                    / f"{logical_id:08x}_{image_index:02d}.{suffix}"
                                )
                                image_path.write_bytes(payload)
                                image_output_rel = rel_to(out_dir, image_path)
                            images_handle.write(
                                f"{logical_id:08x}\t{group}\t{physical_text_no}\t"
                                f"{image_start}\t{len(payload)}\t{suffix}\t{digest}\t"
                                f"{image_output_rel}\n"
                            )
                            embedded_image_count += 1

                        if fragments:
                            text_block_count += 1
                            text_fragment_count += len(fragments)
                            text_chars = sum(len(fragment) for fragment in fragments)
                            text_char_count += text_chars
                            joined_fragments = "\n".join(fragments)
                            text_handle.write(
                                f"{logical_id:08x}\t{group}\t{physical_text_no}\t"
                                f"{xdf_offset}\t{stored_size}\t{len(decoded)}\t"
                                f"{tsv_escape(joined_fragments)}\n"
                            )
                            plain_text_handle.write(f"\n[{logical_id:08x}]\n")
                            for fragment in fragments:
                                plain_text_handle.write(fragment)
                                plain_text_handle.write("\n")
                        else:
                            text_chars = 0

                    except Exception as exc:  # noqa: BLE001 - keep batch dumps moving.
                        error = str(exc)
                        error_count += 1
                        text_chars = 0

                    blocks_handle.write(
                        f"{logical_id:08x}\t{group}\t{physical_text_no}\t"
                        f"{xdf_offset}\t{stored_size}\t{len(decoded)}\t"
                        f"{len(fragments)}\t{text_chars}\t{len(layout_records)}\t"
                        f"{len(embedded_ranges)}\t"
                        f"{decoded_output_rel or ''}\t{tsv_escape(error)}\n"
                    )
                    summaries.append(
                        BodyBlockSummary(
                            logical_id=logical_id,
                            group=group,
                            physical_text_no=physical_text_no,
                            xdf_offset=xdf_offset,
                            stored_size=stored_size,
                            decoded_size=len(decoded),
                            text_fragment_count=len(fragments),
                            text_char_count=text_chars,
                            layout_record_count=len(layout_records),
                            embedded_images=len(embedded_ranges),
                            decoded_output=decoded_output_rel,
                        )
                    )
                    decoded_count += 1

                if stop:
                    break

            if html_handle is not None:
                write_body_layout_html_footer(html_handle)
    finally:
        for handle in xdf_handles.values():
            handle.close()

    return {
        "enabled": True,
        "blocks_decoded": decoded_count,
        "errors": error_count,
        "text_blocks": text_block_count,
        "text_fragments": text_fragment_count,
        "text_chars": text_char_count,
        "layout_records": layout_record_count,
        "html_pages": html_page_count,
        "skqs_map": str(resolved_skqs_map_path) if resolved_skqs_map_path else None,
        "skqs_text_replacements": skqs_text_replacement_count,
        "skqs_layout_replacements": skqs_layout_replacement_count,
        "embedded_images": embedded_image_count,
        "body_blocks_manifest": rel_to(out_dir, blocks_tsv),
        "body_text_fragments": rel_to(out_dir, text_tsv),
        "body_text": rel_to(out_dir, text_txt),
        "body_layout_records": rel_to(out_dir, layout_tsv) if write_layout else None,
        "body_layout_rows": rel_to(out_dir, layout_rows_txt) if write_layout else None,
        "body_layout_html": rel_to(out_dir, layout_html) if write_html else None,
        "embedded_images_manifest": rel_to(out_dir, images_tsv),
        "decoded_blocks_written": write_decoded_blocks,
        "body_layout_written": write_layout,
        "body_html_written": write_html,
        "body_image_mode": body_image_mode,
        "sample": [summary.__dict__ for summary in summaries[:20]],
    }


def collect_xdf_volumes(root: Path) -> list[dict[str, object]]:
    server = root / "4KServer"
    volumes = sorted(server.glob("[0-9][0-9][0-9]/Text*.xdf"))
    return [
        {
            "path": rel_to(root, path),
            "size": path.stat().st_size,
        }
        for path in volumes
    ]


def collect_fts_indexes(root: Path) -> list[dict[str, object]]:
    server = root / "4KServer"
    index_exts = {".atc", ".boo", ".dic", ".pag", ".seg", ".xnx"}
    paths = sorted(
        path
        for path in server.rglob("*")
        if path.is_file() and path.suffix.lower() in index_exts
    )
    return [
        {
            "path": rel_to(root, path),
            "size": path.stat().st_size,
            "suffix": path.suffix.lower(),
        }
        for path in paths
    ]


def collect_database_indexes(root: Path) -> list[dict[str, object]]:
    database_dirs = [root / "Database", root / "4KServer" / "Database"]
    idx_files: list[Path] = []
    for database_dir in database_dirs:
        if database_dir.is_dir():
            idx_files.extend(sorted(database_dir.glob("*.Idx")))
            idx_files.extend(sorted(database_dir.glob("*.idx")))

    indexes: list[dict[str, object]] = []
    for path in sorted(set(idx_files)):
        size = path.stat().st_size
        candidates = [record_size for record_size in COMMON_RECORD_SIZES if size % record_size == 0]
        guessed = KNOWN_DB_INDEX_RECORD_SIZES.get(path.name)
        indexes.append(
            {
                "path": rel_to(root, path),
                "size": size,
                "record_size_guess": guessed,
                "record_count_guess": size // guessed if guessed else None,
                "candidate_record_sizes": candidates,
            }
        )

    return indexes


def inspect_image_cds(root: Path) -> dict[str, object]:
    server = root / "4KServer"
    expected = [f"{i:03d}" for i in range(165)]
    present = [name for name in expected if (server / name).is_dir()]
    missing = [name for name in expected if name not in present]
    cdpaths = server / "Etc" / "CdPaths.conf"
    return {
        "expected_range": "000-164",
        "present_count": len(present),
        "missing_count": len(missing),
        "present": present,
        "missing": missing,
        "cdpaths_conf": rel_to(root, cdpaths) if cdpaths.exists() else None,
    }


def write_manifest(
    root: Path,
    out_dir: Path,
    text_tables: list[TextTableSummary],
    images: list[ImageSummary],
    image_mode: str,
    body_summary: dict[str, object] | None,
) -> None:
    manifest = {
        "input_root": str(root),
        "output_root": str(out_dir),
        "text_tables": [summary.__dict__ for summary in text_tables],
        "images": {
            "mode": image_mode,
            "count": len(images),
            "manifest": "images_manifest.tsv" if image_mode != "none" else None,
        },
        "xdf_text_volumes": collect_xdf_volumes(root),
        "database_indexes": collect_database_indexes(root),
        "fts_indexes": collect_fts_indexes(root),
        "image_cds": inspect_image_cds(root),
        "body_text": body_summary or {"enabled": False},
        "notes": [
            "Database/*.Dat files are UTF-16LE null-terminated string pools and are dumped to TSV.",
            "Plain image assets are copied or listed by extension and magic header.",
            "With --dump-body, Text000*.xdf blocks are decoded through level1/level2 indexes, the 4kText.exe IDEA schedule, and 4kqs.frq Huffman frequency tables.",
            "CdPaths.conf in this package names CD000-CD164 as image CDs. If the 000-164 directories are missing, original scanned page image CDs are not present in this local copy.",
        ],
    }
    with (out_dir / "manifest.json").open("w", encoding="utf-8") as handle:
        json.dump(manifest, handle, ensure_ascii=False, indent=2)
        handle.write("\n")


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Dump 4KBrowser metadata, images, and optionally decoded XDF body blocks."
    )
    parser.add_argument("root", type=Path, help="Path to the 4KBrowser directory.")
    parser.add_argument(
        "--out",
        type=Path,
        default=Path("4kbrowser_dump"),
        help="Output directory. Default: ./4kbrowser_dump",
    )
    parser.add_argument(
        "--limit-rows",
        type=int,
        default=None,
        help="Write only the first N rows of each .Dat table, useful for sampling.",
    )
    parser.add_argument(
        "--no-text-tables",
        action="store_true",
        help="Skip Database/*.Dat UTF-16LE table dumps.",
    )
    parser.add_argument(
        "--image-mode",
        choices=("copy", "manifest", "none"),
        default="copy",
        help="copy images, only list them, or skip images. Default: copy",
    )
    parser.add_argument(
        "--limit-images",
        type=int,
        default=None,
        help="Process only the first N images, useful for sampling.",
    )
    parser.add_argument(
        "--dump-body",
        action="store_true",
        help="Decode Text000*.xdf body blocks into text fragments and embedded-image data.",
    )
    parser.add_argument(
        "--body-limit",
        type=int,
        default=None,
        help="Decode only the first N body blocks, useful for sampling.",
    )
    parser.add_argument(
        "--body-start",
        type=lambda value: int(value, 0),
        default=None,
        help="Start body decoding at this logical ID. Hex like 0x00010005 is accepted.",
    )
    parser.add_argument(
        "--body-end",
        type=lambda value: int(value, 0),
        default=None,
        help="Stop body decoding after this logical ID. Hex like 0x00010020 is accepted.",
    )
    parser.add_argument(
        "--body-write-decoded",
        action="store_true",
        help="Also write each fully decoded binary body block.",
    )
    parser.add_argument(
        "--body-layout",
        action="store_true",
        help="Also write structured original text layout records from decoded body blocks.",
    )
    parser.add_argument(
        "--body-html",
        action="store_true",
        help="Also write a browsable static HTML page from body layout records.",
    )
    parser.add_argument(
        "--body-image-mode",
        choices=("extract", "manifest", "none"),
        default="extract",
        help="Extract embedded images from decoded body blocks, only list them, or skip them.",
    )
    parser.add_argument(
        "--body-min-text-chars",
        type=int,
        default=2,
        help="Minimum UTF-16LE text run length to keep from decoded body blocks. Default: 2.",
    )
    parser.add_argument(
        "--skqs-map",
        type=Path,
        default=None,
        help=(
            "Optional SKQS character comparison table, either skqs.json or the "
            "skqs.html file that references it. Body text outputs are normalized "
            "through this map."
        ),
    )
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    root = args.root.expanduser().resolve()
    out_dir = args.out.expanduser().resolve()

    if not root.is_dir():
        raise SystemExit(f"Input root is not a directory: {root}")

    out_dir.mkdir(parents=True, exist_ok=True)

    text_tables: list[TextTableSummary] = []
    if not args.no_text_tables:
        text_tables = dump_text_tables(root, out_dir, args.limit_rows)

    images: list[ImageSummary] = []
    if args.image_mode != "none":
        images = dump_images(root, out_dir, args.image_mode, args.limit_images)

    body_summary: dict[str, object] | None = None
    if args.dump_body:
        body_summary = dump_body_blocks(
            root=root,
            out_dir=out_dir,
            limit_blocks=args.body_limit,
            start_logical_id=args.body_start,
            end_logical_id=args.body_end,
            write_decoded_blocks=args.body_write_decoded,
            write_layout=args.body_layout,
            write_html=args.body_html,
            body_image_mode=args.body_image_mode,
            min_text_chars=args.body_min_text_chars,
            skqs_map_path=args.skqs_map,
        )

    write_manifest(root, out_dir, text_tables, images, args.image_mode, body_summary)

    print(f"input: {root}")
    print(f"output: {out_dir}")
    print(f"text tables dumped: {len(text_tables)}")
    print(f"images processed: {len(images)} ({args.image_mode})")
    if body_summary:
        print(f"body blocks decoded: {body_summary['blocks_decoded']}")
        print(f"body text fragments: {body_summary['text_fragments']}")
        if body_summary.get("body_layout_written") or body_summary.get("body_html_written"):
            print(f"body layout records: {body_summary['layout_records']}")
        if body_summary.get("body_html_written"):
            print(f"body HTML pages: {body_summary['html_pages']}")
        if body_summary.get("skqs_map"):
            print(f"SKQS character replacements: {body_summary['skqs_text_replacements']} text, {body_summary['skqs_layout_replacements']} layout")
        print(f"body embedded images: {body_summary['embedded_images']}")
    print(f"manifest: {out_dir / 'manifest.json'}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
