#!/usr/bin/env node
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import process from 'node:process';
import { createHook } from './_runtime.mjs';

const EDIT_TOOLS = new Set(['Edit', 'Write', 'create_file', 'editFiles', 'replace_string_in_file']);
const counterPath = path.join(os.tmpdir(), `aikit-edit-count-${process.ppid}.json`);
const readCount = () => {
  try {
    return JSON.parse(fs.readFileSync(counterPath, 'utf8')).count || 0;
  } catch {
    return 0;
  }
};
const writeCount = (count) => {
  try {
    fs.writeFileSync(counterPath, JSON.stringify({ count }), 'utf8');
  } catch {}
};

/** Tracks edit counts and nudges validation after repeated file changes. */
export const postEditCheck = async (context) => {
  if (context.event !== 'PostToolUse' || !EDIT_TOOLS.has(context.toolName))
    return { decision: 'allow' };
  const count = readCount() + 1;
  writeCount(count);
  if (count < 5 || count % 5 !== 0) return { decision: 'allow' };
  const prefix = count >= 10 ? 'Strongly consider' : 'Consider';
  return {
    additionalContext: `📋 You've made ${count} file edits this session. ${prefix} running check({}) and test_run({}) to validate changes before continuing.`,
  };
};

createHook(postEditCheck);
