#import "@preview/cmarker:0.1.8": render-with-metadata
#import "config.typ": *
#import "theme.typ": *

#let underline-accent(body) = underline(
  body,
  stroke: 1.5pt + color-primary,
  offset: 4pt,
  evade: true,
)

#let text-highlight(body) = highlight(
  body,
  fill: color-accent-surface,
  top-edge: "ascender",
  bottom-edge: "descender",
  radius: tw(0.5),
)

#let parse-report-date(raw) = {
  if type(raw) == datetime {
    raw
  } else if type(raw) == str {
    let parts = raw.split("-")
    if parts.len() == 3 {
      datetime(
        year: int(parts.at(0)),
        month: int(parts.at(1)),
        day: int(parts.at(2)),
      )
    } else {
      none
    }
  } else {
    none
  }
}

#let source-dir(path) = {
  let parts = path.split("/")
  if parts.len() <= 1 {
    ""
  } else {
    parts.slice(0, parts.len() - 1).join("/")
  }
}

#let resolve-image(source-path, source, alt: none) = {
  let dir = source-dir(source-path)
  let full = if dir == "" { source } else { dir + "/" + source }
  let path = "../" + full
  let img = image(path, width: image-max-width, fit: "contain")
  if alt != none and alt != "" {
    block(width: 100%)[
      #align(center)[#img]
      #v(space-micro)
      #align(center)[
        #text(size: size-caption, fill: color-caption)[#alt]
      ]
    ]
  } else {
    img
  }
}

#let meta-string(meta, key, fallback) = {
  let value = meta.at(key, default: none)
  if value == none {
    fallback
  } else if type(value) == str {
    value
  } else {
    str(value)
  }
}

#let merge-meta(yaml) = (
  title: meta-string(yaml, "title", default-title),
  brand: meta-string(yaml, "brand", default-brand),
  company: meta-string(yaml, "company", default-company),
  version: meta-string(yaml, "version", default-version),
  date: meta-string(yaml, "date", default-date),
  summary: yaml.at("summary", default: ""),
)

#let load-report-md(markdown, source-path: content-path, extra-scope: (:)) = {
  let (yaml, body) = render-with-metadata(
    markdown,
    metadata-block: "frontmatter-yaml",
    smart-punctuation: true,
    html: (
      u: (_, body) => underline-accent(body),
      mark: (_, body) => text-highlight(body),
    ),
    scope: (
      image: (source, alt: none) => resolve-image(source-path, source, alt: alt),
      ..extra-scope,
    ),
  )
  (
    metadata: merge-meta(if yaml == none { (:) } else { yaml }),
    body: body,
  )
}
