-- Parts are level-one headings. Ordinary level-two headings are chapters and
-- receive their stable number from SUMMARY.md order, not from hand-authored
-- Markdown. A level-two heading marked `.case` becomes a level-three case
-- identity, and its subsections move down with it without consuming a chapter.
local chapter = 0
local unnumbered_section = false
local case_section = false

local function has_class(classes, expected)
  for _, class in ipairs(classes) do
    if class == expected then
      return true
    end
  end
  return false
end

function Header(header)
  if header.level == 1 then
    unnumbered_section = has_class(header.classes, "unnumbered")
    case_section = false
    return nil
  end
  if header.level == 2 and has_class(header.classes, "case") then
    local case_id = header.attributes["data-case-id"]
    if case_id == nil or not string.match(case_id, "^%d%d%d$") then
      error("case heading requires data-case-id with exactly three digits")
    end
    local prefix = pandoc.Inlines({
      pandoc.Str("案例"),
      pandoc.Space(),
      pandoc.Str(case_id .. "｜"),
    })
    prefix:extend(header.content)
    header.content = prefix
    case_section = true
    header.level = 3
    return header
  end
  if case_section and header.level >= 3 then
    header.level = header.level + 1
    return header
  end
  if header.level ~= 2 then
    return nil
  end
  case_section = false
  if unnumbered_section then
    return nil
  end
  chapter = chapter + 1
  local prefix = pandoc.Inlines({
    pandoc.Str("第"),
    pandoc.Space(),
    pandoc.Str(tostring(chapter)),
    pandoc.Space(),
    pandoc.Str("章"),
    pandoc.Space(),
  })
  prefix:extend(header.content)
  header.content = prefix
  return header
end
