import fs from "fs";
import path from "path";

const __dirname = path.dirname(new URL(import.meta.url).pathname);
const projectRoot = path.resolve(__dirname, "..");
const gitHooksDir = path.join(projectRoot, ".git", "hooks");
const hookPath = path.join(gitHooksDir, "pre-commit");

const hookScript = `#!/bin/sh
# Pre-commit hook to run tests before committing code
echo "🔍 Running pre-commit tests..."

# Check if npm is installed and runnable
if ! command -v npm >/dev/null 2>&1; then
    echo "⚠️ npm is not found in path. Skipping test check."
    exit 0
fi

# Run the test suite
npm run test
status=$?

if [ $status -ne 0 ]; then
  echo "❌ Tests failed. Commit aborted."
  exit 1
fi

echo "✅ All tests passed! Proceeding with commit."
exit 0
`;

function setupHook() {
  if (!fs.existsSync(path.join(projectRoot, ".git"))) {
    console.log("⚠️ Not a git repository or .git folder not found. Skipping hook setup.");
    return;
  }

  try {
    if (!fs.existsSync(gitHooksDir)) {
      fs.mkdirSync(gitHooksDir, { recursive: true });
    }

    fs.writeFileSync(hookPath, hookScript, { encoding: "utf8", mode: 0o755 });
    
    // Explicitly enforce permissions via chmodSync to ensure it's executable
    fs.chmodSync(hookPath, 0o755);
    
    console.log("✅ Git pre-commit hook set up successfully at .git/hooks/pre-commit");
  } catch (error) {
    console.error("❌ Failed to set up Git pre-commit hook:", error.message);
  }
}

setupHook();
