// src/commands/validate-cross-check.ts
import * as fs from "fs";
import * as path from "path";
import { execSync } from "child_process";
import { Ok } from "@harness-engineering/core";
function findFiles(dir, ext) {
  if (!fs.existsSync(dir)) return [];
  return fs.readdirSync(dir).filter((f) => f.endsWith(ext)).map((f) => path.join(dir, f));
}
function extractPlannedFiles(planContent) {
  const files = [];
  const regex = /- (?:Create|Modify):\s*`([^`]+)`/g;
  let match;
  while ((match = regex.exec(planContent)) !== null) {
    files.push(match[1]);
  }
  return files;
}
function getFileModTime(filePath, projectPath) {
  try {
    const output = execSync(`git log -1 --format=%aI -- "${filePath}"`, {
      cwd: projectPath,
      encoding: "utf-8",
      stdio: ["pipe", "pipe", "pipe"]
    }).trim();
    return output ? new Date(output) : null;
  } catch {
    return null;
  }
}
async function runCrossCheck(options) {
  const result = {
    specToPlan: [],
    planToImpl: [],
    staleness: [],
    warnings: 0
  };
  const planFiles = findFiles(options.plansDir, ".md");
  for (const planFile of planFiles) {
    const content = fs.readFileSync(planFile, "utf-8");
    const plannedFiles = extractPlannedFiles(content);
    const planName = path.basename(planFile);
    for (const file of plannedFiles) {
      const fullPath = path.join(options.projectPath, file);
      if (!fs.existsSync(fullPath)) {
        result.planToImpl.push(`${planName}: planned file not found: ${file}`);
        result.warnings++;
      }
    }
    const planModTime = getFileModTime(planFile, options.projectPath);
    if (planModTime) {
      for (const file of plannedFiles) {
        const fullPath = path.join(options.projectPath, file);
        if (fs.existsSync(fullPath)) {
          const implModTime = getFileModTime(fullPath, options.projectPath);
          if (implModTime && implModTime > planModTime) {
            result.staleness.push(`${planName}: implementation newer than plan (${file})`);
            result.warnings++;
            break;
          }
        }
      }
    }
  }
  return Ok(result);
}
export {
  runCrossCheck
};
