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

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
cd "${SCRIPT_DIR}"

for calibration_run in 1 2 3; do
    IPZ_VISUAL_CALIBRATION_RUN="${calibration_run}" ./run-playwright.sh test universal-admin-component-redesign.spec.js --project=chromium
done
./run-playwright.sh test universal-admin-assertions.spec.js --project=chromium
./run-playwright.sh test fields-table-overflow.spec.js --project=chromium
./run-playwright.sh test universal-admin-component-redesign.spec.js --project=chromium

readonly -a GENERATE_ALL_SPECS=(
    "journeys/UJ-021-generate-all-content.spec.js"
    "live-batch-proof.spec.js"
)
readonly -a GENERATE_ALL_PROJECTS=("chromium" "firefox")
readonly -a GENERATE_ALL_TITLES=(
    "UJ-021 Generate All admits one manifest, replays an ambiguous request, and restores multiple manifests after navigation"
    "admits 1,000 intents without request-time preparation, drains bounded work, and reconciles callbacks"
    "recovers every named crash boundary with one generation and proves selective retry"
)
readonly EXPECTED_TESTS_PER_PROJECT="${#GENERATE_ALL_TITLES[@]}"
readonly EXPECTED_GENERATE_ALL_TESTS="$((EXPECTED_TESTS_PER_PROJECT * ${#GENERATE_ALL_PROJECTS[@]}))"

inventory_file="$(mktemp)"
trap 'rm -f -- "${inventory_file}"' EXIT

./run-playwright.sh test "${GENERATE_ALL_SPECS[@]}" \
    --project=chromium \
    --project=firefox \
    --list \
    --reporter=list | tee "${inventory_file}"

for project in "${GENERATE_ALL_PROJECTS[@]}"; do
    discovered=0
    for title in "${GENERATE_ALL_TITLES[@]}"; do
        matches=0
        while IFS= read -r line; do
            if [[ "${line}" == *"[${project}]"* && "${line}" == *"${title}"* ]]; then
                matches=$((matches + 1))
            fi
        done < "${inventory_file}"
        if [[ "${matches}" -ne 1 ]]; then
            printf 'Generate All inventory mismatch for %s / %s: expected 1, found %s.\n' "${project}" "${title}" "${matches}" >&2
            exit 1
        fi
        discovered=$((discovered + matches))
    done
    listed=0
    while IFS= read -r line; do
        if [[ "${line}" == *"[${project}]"* && "${line}" == *"›"* ]]; then
            listed=$((listed + 1))
        fi
    done < "${inventory_file}"
    if [[ "${discovered}" -ne "${EXPECTED_TESTS_PER_PROJECT}" || "${listed}" -ne "${EXPECTED_TESTS_PER_PROJECT}" ]]; then
        printf 'Generate All inventory mismatch for %s: expected %s exact tests, matched %s expected titles across %s listed tests.\n' "${project}" "${EXPECTED_TESTS_PER_PROJECT}" "${discovered}" "${listed}" >&2
        exit 1
    fi
done

./run-playwright.sh test "${GENERATE_ALL_SPECS[@]}" \
    --project=chromium \
    --project=firefox

EXPECTED_GENERATE_ALL_TESTS="${EXPECTED_GENERATE_ALL_TESTS}" node <<'NODE'
const fs = require('fs');
const path = require('path');

const expectedTests = Number(process.env.EXPECTED_GENERATE_ALL_TESTS);
const resultsDir = path.resolve('test-results');
const junitPath = path.join(resultsDir, 'junit.xml');
if (!fs.existsSync(junitPath) || fs.statSync(junitPath).size === 0) {
    throw new Error(`Generate All durable JUnit proof is missing or empty: ${junitPath}`);
}
const junit = fs.readFileSync(junitPath, 'utf8');
const testcases = (junit.match(/<testcase\b/g) || []).length;
const skipped = (junit.match(/<skipped\b/g) || []).length;
const failures = (junit.match(/<failure\b/g) || []).length;
const errors = (junit.match(/<error\b/g) || []).length;
if (testcases !== expectedTests || skipped !== 0 || failures !== 0 || errors !== 0) {
    throw new Error(`Generate All result mismatch: expected ${expectedTests} tests; observed tests=${testcases}, skipped=${skipped}, failures=${failures}, errors=${errors}.`);
}

const files = [];
const walk = (directory) => {
    for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
        const absolute = path.join(directory, entry.name);
        if (entry.isDirectory()) walk(absolute);
        else files.push(absolute);
    }
};
walk(resultsDir);
for (const project of ['chromium', 'firefox']) {
    for (const suffix of ['reconciliation.json', 'success.png']) {
        const matches = files.filter((file) => file.includes(`${project}-${suffix}`) && fs.statSync(file).size > 0);
        if (matches.length !== 3) {
            throw new Error(`Generate All durable ${project} ${suffix} artifacts: expected 3 non-empty files, found ${matches.length}.`);
        }
    }
}
console.log(`Generate All proof inventory passed: ${testcases} tests, zero skipped, 12 non-empty browser artifacts.`);
NODE
