import { readFile, access } from 'node:fs/promises';
import path from 'node:path';
import { fail, pass, repositoryRoot } from './lib.mjs';

const required = [
  'docs/PHASE_16_IMPLEMENTATION_AND_LAUNCH_REPORT_v1.0.md',
  'docs/DECISION_LOG_v16.0.md',
  'docs/IMPLEMENTATION_ISSUE_REGISTER_v1.6.csv',
  'docs/phase16/FINAL_LAUNCH_STATUS_v1.0.md',
  'docs/phase16/LAUNCH_AUTHORIZATION_RECORD_v1.0.md',
  'docs/phase16/FINAL_RELEASE_GATE_MATRIX_v1.0.csv',
  'docs/phase16/COMMAND_AND_PLATFORM_ACTION_MATRIX_v1.0.csv',
  'docs/phase16/DEFERRED_WORK_REGISTER_v1.0.csv',
  'docs/phase16/FEATURE_FLAG_RELEASE_STATE_v1.0.csv',
  'docs/phase16/SECRET_PROVISIONING_RECORD_v1.0.csv',
];
const failures = [];
for (const file of required) {
  try {
    await access(path.join(repositoryRoot, file));
  } catch {
    failures.push(`Missing required Phase 16 artifact: ${file}`);
  }
}
const status = await readFile(
  path.join(repositoryRoot, 'docs/phase16/FINAL_LAUNCH_STATUS_v1.0.md'),
  'utf8',
);
const auth = await readFile(
  path.join(repositoryRoot, 'docs/phase16/LAUNCH_AUTHORIZATION_RECORD_v1.0.md'),
  'utf8',
);
const flags = await readFile(
  path.join(repositoryRoot, 'docs/phase16/FEATURE_FLAG_RELEASE_STATE_v1.0.csv'),
  'utf8',
);
const secrets = await readFile(
  path.join(repositoryRoot, 'docs/phase16/SECRET_PROVISIONING_RECORD_v1.0.csv'),
  'utf8',
);
if (!status.includes('Launch aborted before deployment'))
  failures.push('Final launch status is missing or inconsistent.');
if (!auth.includes('**Rejected**'))
  failures.push('Launch authorization is not explicitly rejected.');
if (
  /\btrue\b/.test(
    flags
      .split('\n')
      .slice(1)
      .map((line) => line.split(',')[1])
      .join('\n'),
  )
)
  failures.push('A Phase 16 production feature flag is enabled.');
if (
  !secrets.includes('No production credentials exist') &&
  !secrets.includes('No credential supplied')
)
  failures.push(
    'Secret provisioning record does not explicitly preserve missing credentials as blockers.',
  );
if (failures.length) fail(failures);
else
  pass(
    'Phase 16 no-go governance, disabled feature state, blocked approvals, and evidence package are explicit and internally consistent.',
  );
