import type { ToolCall } from '../../llm/openai-compat.js';

/**
 * Cache invalidation triggers derived from a tool call.
 *
 * Phase 2 only emits triggers for the side-effecting tools we actually
 * understand:
 *   - `Edit` / `Write`  → invalidate cached Reads of `file_path`
 *   - `Bash`            → invalidate every file-derived entry (we cannot
 *                         enumerate what an arbitrary shell command touched)
 *
 * Read-only tools (Read, Grep, Glob, …) and unknown tool names produce no
 * trigger so the caller can short-circuit.
 */
export type InvalidationTrigger =
  | { kind: 'path'; path: string }
  | { kind: 'all_files' };

export function extractInvalidationTrigger(toolCall: ToolCall): InvalidationTrigger | null {
  const toolName = toolCall.function.name;

  if (toolName === 'Edit' || toolName === 'Write') {
    let args: Record<string, unknown>;
    try {
      args = JSON.parse(toolCall.function.arguments) as Record<string, unknown>;
    } catch {
      // Conservative: if we cannot parse the args, treat as all-files
      // invalidation rather than silently leaving cache stale.
      return { kind: 'all_files' };
    }
    const filePath = args['file_path'];
    if (typeof filePath === 'string' && filePath.length > 0) {
      return { kind: 'path', path: filePath };
    }
    return { kind: 'all_files' };
  }

  if (toolName === 'Bash') {
    return { kind: 'all_files' };
  }

  return null;
}
