#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
WORK_DIR="$(mktemp -d)"
trap 'rm -rf "$WORK_DIR"' EXIT

mkdir -p "$WORK_DIR/userfront/coverage"

cat > "$WORK_DIR/userfront/coverage/lcov.info" <<'LCOV'
SF:lib/main.dart
DA:1,1
DA:2,0
LF:2
LH:1
end_of_record
SF:lib/i18n_data.dart
DA:1,0
LF:1
LH:0
end_of_record
SF:lib/features/auth/domain/login_challenge_resolver.dart
DA:10,1
DA:11,1
DA:12,0
LF:3
LH:2
end_of_record
SF:lib/core/services/logout_service.dart
DA:20,1
DA:21,1
LF:2
LH:2
end_of_record
LCOV

(
  cd "$WORK_DIR"
  node "$ROOT_DIR/scripts/summarize_flutter_coverage.mjs" userfront
)

node - "$WORK_DIR/reports/package-coverage-summary.json" <<'NODE'
const fs = require("node:fs");

const summary = JSON.parse(fs.readFileSync(process.argv[2], "utf8"));
const row = summary.packages[0];

function assertEqual(actual, expected, message) {
  if (actual !== expected) {
    throw new Error(`${message}: expected ${expected}, got ${actual}`);
  }
}

assertEqual(row.package, "userfront", "package name");
assertEqual(row.statements, 80, "line coverage must exclude bootstrap/generated files");
assertEqual(row.lines, 80, "lines coverage must match statements for Flutter lcov");
assertEqual(row.coveredLines, 4, "covered lines");
assertEqual(row.totalLines, 5, "total lines");
assertEqual(row.lcovPath, "userfront/coverage/lcov.info", "lcov path");
NODE

grep -Fq "| userfront | 80.00% | 4 / 5 | userfront/coverage/lcov.info |" \
  "$WORK_DIR/reports/userfront-coverage-summary.md"

echo "OK: userfront Flutter LCOV summary is generated"
