---
title: "File Comparison Report"
output:
  html_document:
    theme: flatly
    highlight: tango
    self_contained: true
params:
  # Comparison data frame containing file paths, results and comments
  dt:       NULL
  # Optional string pattern used to omit rows from comparisons
  omit_val: NULL
  # Used verifyr2 library version
  version:  NULL
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)

dt         <- params$dt
omit_val   <- params$omit_val
version    <- params$version
n_total    <- nrow(dt)
n_match    <- sum(grepl("No differences", dt$comparison))
n_mismatch <- n_total - n_match
gh_link    <- "https://github.com/ejuhjav/verifyr2"

# Pre-render all FAIL diffs
diff_results <- vector("list", n_total)

# Initialise config once outside the loop
opts <- verifyr2::Config$new()
opts$set("details.mode", "summary")
opts$set("generic.level", "word")

for (i in seq_len(n_total)) {
  if (grepl("No differences", dt$comparison[i])) next

  comparator <- verifyr2::create_comparator(dt$file1[i], dt$file2[i])

  details <- tryCatch(
    comparator$vrf_details(config = opts, omit = omit_val),
    error = function(e) {
      list(list(
        type    = "text",
        content = paste0(
          "<p style='color:red;'>Error: ", conditionMessage(e), "</p>"
        )
      ))
    }
  )

  # Collect all detail items — a file can return multiple items
  item_html <- htmltools::tagList()

  for (d in details) {
    content <- d$content

    # S4 object returned by diffobj is not directly compatible with htmltools
    if ("text" == d$type) {
      content <- htmltools::HTML(as.character(content))
    }

    item_html <- htmltools::tagAppendChildren(
      item_html,
      content
    )
  }

  diff_results[[i]] <- item_html
}
```

```{r load_styles, results='asis', echo=FALSE}
css_file1 <- "report_styles.css"
css_file2 <- "image_diff_styles.css"

if (file.exists(css_file1) && file.exists(css_file2)) {
  htmltools::tags$style(
    includeText(css_file1),
    includeText(css_file2)
  )
}

```

```{r header, results='asis'}
logo_path <- "verifyr2.ico"
logo_tag  <- NULL
omit_tag  <- NULL

if (file.exists(logo_path)) {
  logo_tag <- htmltools::tags$a(
    href = gh_link,
    title = "verifyr2 in github",
    target = "_blank",
    htmltools::tags$img(
      src = paste0(
        "data:image/x-icon;base64,",
        base64enc::base64encode(logo_path)
      )
    )
  )
}

if (!is.null(omit_val)) {
  omit_tag <- tagList(
    " \u00a0|\u00a0 ", # Safe unicode for &nbsp;
    htmltools::tags$strong("Omit pattern:"), " ",
    htmltools::tags$code(omit_val)
  )
}

report_header <- htmltools::tags$div(
  class = "report-header",
  logo_tag,
  htmltools::tags$strong("Generated:"),
  " ",
  format(Sys.time(), "%Y-%m-%d %H:%M:%S"),
  omit_tag,
  " \u00a0|\u00a0 ",
  htmltools::tags$strong("Generated with"), " ",
  htmltools::tags$a(
    href = gh_link,
    title = "verifyr2 in github",
    target = "_blank",
    paste0("verifyr2 (v", version, ")")
  )
)

report_header
```

## Overview

```{r overview}
htmltools::tags$table(
  class = "summary-table",

  htmltools::tags$thead(
    htmltools::tags$tr(
      htmltools::tags$th("Total files"),
      htmltools::tags$th("Match"),
      htmltools::tags$th("Mismatch")
    )
  ),

  htmltools::tags$tr(
    htmltools::tags$td(n_total),

    htmltools::tags$td(
      htmltools::tags$span(
        class = "summary-match",
        n_match
      )
    ),

    htmltools::tags$td(
      htmltools::tags$span(
        class = "summary-mismatch",
        n_mismatch
      )
    )
  )
)
```

## Summary

```{r summary_table}
status_badge <- function(comparison_result) {
  if (grepl("No differences", comparison_result)) {
    htmltools::tags$span(
      class = "status-badge badge-match",
      "Match"
    )
  } else {
    htmltools::tags$span(
      class = "status-badge badge-mismatch",
      "Mismatch"
    )
  }
}

rows <- lapply(seq_len(nrow(dt)), function(i) {
  htmltools::tags$tr(
    # File name as link
    htmltools::tags$td(
      htmltools::tags$a(
        href = paste0("#detail-", i),
        basename(dt$file1[i])
      )
    ),
    # Result
    htmltools::tags$td(
      dt$comparison[i]
    ),
    # Status
    htmltools::tags$td(
      class = "status-column",
      status_badge(dt$comparison[i])
    ),
    # Comments
    htmltools::tags$td(
      if (!is.null(dt$comments_details[i]) && nzchar(dt$comments_details[i])) {
        dt$comments_details[i]
      } else {
        "\u2014"
      }
    )
  )
})

table_html <- htmltools::tags$table(
  class = "diff-table",

  htmltools::tags$thead(
    htmltools::tags$tr(
      htmltools::tags$th("File"),
      htmltools::tags$th("Result"),
      htmltools::tags$th("Status"),
      htmltools::tags$th("Comments")
    )
  ),

  htmltools::tags$tbody(
    tagList(rows)
  )
)

table_html
```

## Details

```{r details, results='asis'}
detail_sections <- lapply(seq_len(nrow(dt)), function(i) {

  file1   <- dt$file1[i]
  file2   <- dt$file2[i]
  result  <- dt$comparison[i]
  comment <- dt$comments_details[i]

  is_pass <- grepl("No differences", result)

  section_class <- if (is_pass) "file-match" else "file-mismatch"
  badge_class   <- if (is_pass) "badge-match" else "badge-mismatch"

  # ---- Comment block (SAFE HTML via tags) ----
  comment_block <- if (!is.null(comment) && nzchar(comment)) {
    htmltools::tags$div(
      class = "comment-box",
      htmltools::tags$strong("Comment:"),
      " ",
      comment
    )
  } else {
    NULL
  }

  # ---- Header ----
  header <- htmltools::tags$div(
    class = "file-header",

    htmltools::tags$span(
      class = "file-name",
      htmltools::tags$strong(basename(file1)),
      " [",
      htmltools::tags$a(href = "#header", "back to top"),
      "]"
    ),

    htmltools::tags$span(
      class = badge_class,
      if (is_pass) "Match" else "Mismatch"
    )
  )

  # ---- Paths ----
  paths <- htmltools::tags$div(
    class = "file-paths",

    htmltools::tags$span(class = "path-label", "Base"),
    htmltools::tags$br(),
    file1,
    htmltools::tags$br(),

    htmltools::tags$span(class = "path-label", "Compare"),
    htmltools::tags$br(),
    file2
  )

  # ---- Result block ----
  result_block <- htmltools::tags$div(
    class = "file-result",
    htmltools::tags$span(result),
    comment_block
  )

  # ---- Diff output ----
  diff_html  <- diff_results[[i]]
  diff_block <- if (is_pass) {
    htmltools::tags$div(
      class = "diff-output match-message",
      htmltools::HTML("&#10003;&nbsp; Files are identical.")
    )
  } else {
    htmltools::tags$div(
      class = "diff-output",
      if (!is.null(diff_html) && length(diff_html) > 0) {
        diff_html
      } else {
        htmltools::tags$p(class = "no-diff", result)
      }
    )
  }

  # ---- Full section ----
  htmltools::tags$div(
    id = paste0("detail-", i),
    class = paste("file-section", section_class),
    header,
    paths,
    result_block,
    diff_block
  )
})

htmltools::tagList(detail_sections)
```
