import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { loadCandidateRecord, validateCoverageEvidence, runWp705Gate, REQUIRED_COVERAGE_UNITS } from '../../scripts/lib/wp7-05-ui-gate.mjs';

test('WP7-05 accepts the WP7-01 candidate record schema', () => {
  const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'wp7-05-'));
  const file = path.join(directory, 'release-candidate.json');
  fs.writeFileSync(file, JSON.stringify({
    browsers: [
      { brand: 'Google Chrome', full_version: '150.0.0', major: 150 },
      { brand: 'Microsoft Edge', full_version: '151.0.0', major: 151 },
    ],
    windows: { build: '26200.8875' },
    candidate_package: { fixed_port: 43121, sha256: 'A'.repeat(64) },
  }));
  assert.equal(loadCandidateRecord(file).status, 'ready');
  fs.rmSync(directory, { recursive: true, force: true });
});

test('WP7-05 requires all 22 coverage units and both exact candidate viewports', () => {
  const result = validateCoverageEvidence({ coverage_units: [], viewports: [] });
  assert.equal(result.status, 'externally_blocked');
  assert.equal(result.code, 'coverage_units_incomplete');
  assert.equal(result.missing.length, REQUIRED_COVERAGE_UNITS.length);
});

test('WP7-05 requires state evidence for every listed coverage unit', () => {
  const result = validateCoverageEvidence({
    coverage_units: REQUIRED_COVERAGE_UNITS.map((page_id) => ({ page_id, states: [] })),
    viewports: [],
  });
  assert.equal(result.code, 'coverage_states_incomplete');
  assert.equal(result.missingStates.length, REQUIRED_COVERAGE_UNITS.length);
});

test('WP7-05 preserves upstream external blockers instead of declaring Green', () => {
  const result = runWp705Gate({
    candidatePath: 'missing-release-candidate.json',
    evidence: null,
    dependencies: { 'TASK-WP7-03': 'externally_blocked' },
  });
  assert.equal(result.status, 'externally_blocked');
  assert.equal(result.code, 'candidate_record_missing');
});
