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

const manifestPath = path.join(repositoryRoot, 'PHASE_10_PACKAGE_MANIFEST_v1.0.json');
const manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
const failures = [];

if (manifest.project !== 'RentalDriveGo' || manifest.phase !== 10) {
  failures.push('Phase 10 manifest identity is invalid.');
}
if (manifest.file_count !== manifest.files.length) {
  failures.push(
    `Manifest file_count ${manifest.file_count} does not match ${manifest.files.length} entries.`,
  );
}
for (const entry of manifest.files) {
  const filePath = path.join(repositoryRoot, entry.path);
  try {
    const details = await stat(filePath);
    if (details.size !== entry.bytes) failures.push(`${entry.path}: byte size changed.`);
    const digest = await sha256(filePath);
    if (digest !== entry.sha256) failures.push(`${entry.path}: SHA-256 changed.`);
  } catch {
    failures.push(`${entry.path}: file is missing.`);
  }
}

if (failures.length) fail(failures);
else pass(`Phase 10 package manifest verifies ${manifest.files.length} repository files.`);
