/**
 * mcp-health.js — PreToolUse Hook
 * MCP 伺服器健康檢查，連續失敗後進入 cooldown 避免重複呼叫。
 */
const fs = require('fs');
const os = require('os');
const path = require('path');
const HEALTH_CACHE = path.join(os.homedir(), '.claude', 'mcp-health-cache.json');
let d = '';
process.stdin.on('data', c => d += c);
process.stdin.on('end', () => {
  try {
    const input = JSON.parse(d);
    const toolName = input.tool_name || '';
    const mcpMatch = toolName.match(/^mcp__([^_]+)__/);
    if (!mcpMatch) { process.stdout.write(d); return; }
    const server = mcpMatch[1];
    let health = {};
    try { health = JSON.parse(fs.readFileSync(HEALTH_CACHE, 'utf8')); } catch (e) {}
    const sh = health[server] || { failures: 0, lastFailure: 0 };
    const now = Date.now();
    const cooldownMs = Math.min(30000 * (2 ** (sh.failures - 1)), 600000);
    if (sh.lastFailure && now - sh.lastFailure < cooldownMs) {
      process.stderr.write(`[mcp-health] MCP '${server}' 在 cooldown 中，請等待 ${Math.ceil((cooldownMs - (now - sh.lastFailure)) / 1000)}s\n`);
      process.exit(2);
    }
  } catch (e) {}
  process.stdout.write(d);
});
