#!/usr/bin/env node
import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const reportsDirName = "reports";
const reportsPath = path.join(repoRoot, reportsDirName);

function gitLines(args) {
  try {
    const output = execFileSync("git", args, {
      cwd: repoRoot,
      encoding: "utf8",
      stdio: ["ignore", "pipe", "pipe"]
    }).trim();
    return output ? output.split(/\r?\n/u).filter(Boolean) : [];
  } catch (error) {
    const stderr = error?.stderr?.toString?.().trim();
    throw new Error(stderr || error.message);
  }
}

function statusReportPaths() {
  return gitLines(["status", "--porcelain=v1", "--untracked-files=all", "--", reportsDirName])
    .map((line) => line.slice(3).trim())
    .filter(Boolean);
}

const tracked = gitLines(["ls-files", reportsDirName]);
const staged = gitLines(["diff", "--cached", "--name-only", "--", reportsDirName]);
const workingTree = statusReportPaths();
const exists = existsSync(reportsPath);
const failures = [];

if (exists) failures.push("forbidden repository report directory exists in the worktree");
if (tracked.length > 0) failures.push(`tracked reports files: ${tracked.slice(0, 8).join(", ")}`);
if (staged.length > 0) failures.push(`staged reports files: ${staged.slice(0, 8).join(", ")}`);
if (workingTree.length > 0) failures.push(`working-tree reports files: ${workingTree.slice(0, 8).join(", ")}`);

if (failures.length > 0) {
  process.stderr.write(`${JSON.stringify({
    ok: false,
    status: "blocked",
    taskId: "repo-reports-guard",
    policy: "repository report directories are forbidden; use GitHub issue/PR comments, /tmp, .state, or CI artifacts",
    failures
  }, null, 2)}\n`);
  process.exitCode = 1;
} else {
  process.stdout.write(`${JSON.stringify({
    ok: true,
    status: "pass",
    taskId: "repo-reports-guard",
    checked: ["directory", "tracked", "staged", "working-tree"],
    policy: "repository report directory is absent"
  })}\n`);
}
