#!/usr/bin/env node
import fs from 'node:fs';
import path from 'node:path';

function findPackageJson() {
  const candidates = [
    path.join(process.cwd(), 'package.json'),
    path.join(process.cwd(), 'node_modules', 'vigthoria-cli', 'package.json'),
    path.join(process.env.APPDATA || '', 'npm', 'node_modules', 'vigthoria-cli', 'package.json'),
  ];
  for (const p of candidates) {
    if (p && fs.existsSync(p)) return p;
  }
  return null;
}

function exists(p) {
  try { return fs.existsSync(p); } catch { return false; }
}

const pkgPath = findPackageJson();
if (!pkgPath) {
  console.error('[verify] FAIL: package.json not found in expected locations');
  process.exit(1);
}

const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
const targetVersion = process.argv[2] || String(pkg.version || '');
const baseDir = path.dirname(pkgPath);
const isNodeModulesInstall = baseDir.endsWith(path.join('node_modules', 'vigthoria-cli'));
const projectRoot = isNodeModulesInstall ? baseDir : process.cwd();

const srcUtils = path.join(projectRoot, 'src', 'utils');
const distUtils = path.join(projectRoot, 'dist', 'utils');
const requiredSrc = ['context-ranker.ts', 'post-write-validator.ts', 'task-display.ts', 'workspace-cache.ts'];
const requiredDist = ['context-ranker.js', 'post-write-validator.js', 'task-display.js', 'workspace-cache.js'];

const sourceSnapshotExpected = !isNodeModulesInstall && exists(srcUtils);
const missingSrc = sourceSnapshotExpected ? requiredSrc.filter((f) => !exists(path.join(srcUtils, f))) : [];
const missingDist = requiredDist.filter((f) => !exists(path.join(distUtils, f)));

const report = {
  targetVersion,
  packageVersion: String(pkg.version || ''),
  packageJsonPath: pkgPath,
  projectRoot,
  srcUtils,
  distUtils,
  missingSrc,
  missingDist,
};

console.log(JSON.stringify(report, null, 2));

if (report.packageVersion !== targetVersion) {
  console.error(`[verify] FAIL: version mismatch (${report.packageVersion} != ${targetVersion})`);
  process.exit(1);
}
if (missingSrc.length > 0 || missingDist.length > 0) {
  console.error('[verify] FAIL: required utility modules missing');
  process.exit(1);
}

console.log('[verify] PASS: runtime/source snapshot is consistent');
