import { describe, it, beforeEach } from 'node:test';
import assert from 'node:assert/strict';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';

const exec = promisify(execFile);
const __dirname = fileURLToPath(new URL('.', import.meta.url));
const FIXTURES = resolve(__dirname, '../fixtures');
const POSTURE_BIN = resolve(__dirname, '../../scanners/posture.mjs');

async function runPostureJson(fixturePath) {
  const { stdout } = await exec('node', [POSTURE_BIN, fixturePath, '--json'], {
    timeout: 30000,
    cwd: resolve(__dirname, '../..'),
  });
  return JSON.parse(stdout);
}

describe('posture grade stability — baseline-all-a', () => {
  let result;
  beforeEach(async () => {
    result = await runPostureJson(resolve(FIXTURES, 'baseline-all-a'));
  });

  it('overallGrade is A', () => {
    assert.equal(result.overallGrade, 'A');
  });

  it('every quality area (non-Feature Coverage) has grade A', () => {
    const qualityAreas = result.areas.filter(a => a.name !== 'Feature Coverage');
    for (const area of qualityAreas) {
      assert.equal(area.grade, 'A', `${area.name} has grade ${area.grade}, expected A (score=${area.score})`);
    }
  });

  it('has no critical or high findings across scanners', () => {
    const scanners = result.scannerEnvelope.scanners;
    for (const s of scanners) {
      assert.equal(s.counts.critical, 0, `${s.scanner} has ${s.counts.critical} critical findings`);
      assert.equal(s.counts.high, 0, `${s.scanner} has ${s.counts.high} high findings`);
    }
  });

  it('Token Efficiency area scores grade A or B on baseline', () => {
    const te = result.areas.find(a => a.id === 'token_efficiency');
    assert.ok(te, 'expected token_efficiency area to be present');
    assert.ok(['A', 'B'].includes(te.grade),
      `Token Efficiency grade is ${te.grade}, expected A or B (score=${te.score})`);
  });
});
