#!/usr/bin/env bash
#
# Inject evaluation data into an HTML report template.
#
# Usage:
#   generate-report.sh <data-file> <template> <output>
#
# Arguments:
#   data-file   Path to JSON file containing the report DATA object
#   template    Path to the HTML template (e.g., assets/copr-worker-report-template.html)
#   output      Path for the generated HTML report file
#
# Examples:
#   # Generate a coprocessor worker report
#   ./generate-report.sh /tmp/eval-data.json assets/copr-worker-report-template.html /tmp/feb14-report.html
#
#   # Using the skill directory
#   SKILL_DIR="${HOME}/.config/opencode/skills/autoscaler-dashboard"
#   "${SKILL_DIR}/generate-report.sh" /tmp/eval-data.json \
#     "${SKILL_DIR}/assets/copr-worker-report-template.html" \
#     /tmp/feb14-report.html
#
# The template must contain a /*__REPORT_DATA__*/ marker followed by a default
# data object. This script replaces the marker and default data with the contents
# of the JSON data file.
#
# Template format expected:
#   const DATA = /*__REPORT_DATA__*/{
#     ... default/sample data ...
#   };
#
# Output format:
#   const DATA = <contents of data-file>;

set -e

data_file="${1:?Usage: generate-report.sh <data-file> <template> <output>}"
template="${2:?Missing template path}"
output="${3:?Missing output path}"

if [[ ! -f "${data_file}" ]]; then
	echo "ERROR: Data file not found: ${data_file}" >&2
	exit 1
fi

if [[ ! -f "${template}" ]]; then
	echo "ERROR: Template not found: ${template}" >&2
	exit 1
fi

# Validate the data file is valid JSON
if ! jq empty "${data_file}" 2>/dev/null; then
	echo "ERROR: Data file is not valid JSON: ${data_file}" >&2
	exit 1
fi

# The template has this pattern:
#   const DATA = /*__REPORT_DATA__*/{ ... };
#
# We replace from /*__REPORT_DATA__*/ through the matching }; with the JSON data.
# Uses Python for reliable multi-line replacement with brace-depth tracking.
python3 -c "
import sys

template = open(sys.argv[1]).read()
data = open(sys.argv[2]).read()

marker = '/*__REPORT_DATA__*/'
idx = template.find(marker)
if idx == -1:
    print('ERROR: /*__REPORT_DATA__*/ marker not found in template', file=sys.stderr)
    sys.exit(1)

# Find 'const DATA = ' before the marker
prefix_search = template.rfind('const DATA = ', 0, idx)
if prefix_search == -1:
    print('ERROR: Could not find \"const DATA = \" before marker', file=sys.stderr)
    sys.exit(1)

# Find the matching closing }; after the marker by tracking brace depth.
# The DATA object may contain nested braces, strings, and comments.
start_brace = template.find('{', idx + len(marker))
if start_brace == -1:
    print('ERROR: No opening brace found after marker', file=sys.stderr)
    sys.exit(1)

depth = 0
i = start_brace
in_string = False
string_char = None
in_line_comment = False
in_block_comment = False

while i < len(template):
    c = template[i]

    if not in_string and not in_line_comment and not in_block_comment:
        if c == '/' and i + 1 < len(template):
            if template[i + 1] == '/':
                in_line_comment = True
                i += 2
                continue
            elif template[i + 1] == '*':
                in_block_comment = True
                i += 2
                continue
    if in_line_comment:
        if c == '\n':
            in_line_comment = False
        i += 1
        continue
    if in_block_comment:
        if c == '*' and i + 1 < len(template) and template[i + 1] == '/':
            in_block_comment = False
            i += 2
            continue
        i += 1
        continue
    if in_string:
        if c == '\\\\':
            i += 2
            continue
        if c == string_char:
            in_string = False
        i += 1
        continue
    if c in ('\"', \"'\", '\`'):
        in_string = True
        string_char = c
        i += 1
        continue
    if c == '{':
        depth += 1
    elif c == '}':
        depth -= 1
        if depth == 0:
            end = i + 1
            if end < len(template) and template[end] == ';':
                end += 1
            result = template[:prefix_search] + 'const DATA = ' + data + ';' + template[end:]
            open(sys.argv[3], 'w').write(result)
            print('Created ' + sys.argv[3])
            sys.exit(0)
    i += 1

print('ERROR: Could not find matching closing brace for DATA object', file=sys.stderr)
sys.exit(1)
" "${template}" "${data_file}" "${output}"
