#!/usr/bin/env bun
/**
 * PostToolUse:Bash — .pth detection guard after deploy operations
 *
 * After any SSH command to bigblack involving venv/install/deploy,
 * reminds Claude to verify no .pth file exists. Uses PostToolUse
 * soft-block (decision:block) for Claude visibility.
 *
 * Learned 2026-03-28: .pth with 2 hard links survived rm + venv swap.
 * Nuclear cleanup was required 3 times in one session.
 *
 * @see memory/feedback-pth-shadowing-deploy-hazard.md
 */

interface PostToolUseInput {
  tool_name: string;
  tool_input: {
    command?: string;
    [key: string]: unknown;
  };
  tool_response?: string;
  cwd?: string;
}

async function main(): Promise<void> {
  const stdin = await Bun.stdin.text();
  if (!stdin.trim()) return process.exit(0);

  let input: PostToolUseInput;
  try {
    input = JSON.parse(stdin);
  } catch {
    return process.exit(0);
  }

  if (input.tool_name !== "Bash") return process.exit(0);
  const cmd = input.tool_input?.command || "";
  const response = input.tool_response || "";

  // Only trigger on SSH bigblack commands involving venv/install/deploy
  if (!/ssh\s+bigblack/i.test(cmd)) return process.exit(0);

  const isDeployOp =
    /uv\s+pip\s+install/i.test(cmd) ||
    /\.venv-staging/i.test(cmd) ||
    /mv\s+\.venv/i.test(cmd) ||
    /maturin/i.test(cmd) ||
    /force-reinstall/i.test(cmd);

  if (!isDeployOp) return process.exit(0);

  // Check if the response mentions .pth (already detected inline)
  if (/\.pth/.test(response) && /FATAL|shadowing|editable/i.test(response)) {
    // Already detected — no need to remind
    return process.exit(0);
  }

  // Soft-block: remind Claude to verify no .pth exists
  const reminder = JSON.stringify({
    decision: "block",
    reason:
      "[PTH-GUARD] Deploy operation on bigblack detected. " +
      "VERIFY no .pth shadowing exists:\n" +
      "  ssh bigblack 'ls $(~/opendeviationbar-py/.venv/bin/python3 -c " +
      "\"import site; print(site.getsitepackages()[0])\")/opendeviationbar.pth 2>/dev/null " +
      "&& echo FATAL-PTH-EXISTS || echo OK-NO-PTH'\n\n" +
      "If .pth found: rm it, rm dist-info, reinstall wheel from /tmp/. " +
      "See: memory/feedback-pth-shadowing-deploy-hazard.md",
  });
  console.log(reminder);
  return process.exit(0);
}

void main();
