// ============================================================================
// @h33/mcp — Per-tool attestation helper
//
// Use this when you want fine-grained control over which tools are attested
// rather than wrapping the entire server.
// ============================================================================

import { H33Agent } from '@h33/agent';

/**
 * Definition for an MCP tool with built-in H33 attestation.
 */
export interface AttestedToolDef<T = any, R = any> {
  /** Tool name (becomes h33.tool.mcp.<name>.v1 in the attestation chain) */
  name: string;
  /** Human-readable description */
  description: string;
  /** JSON Schema for the tool's input */
  inputSchema: Record<string, any>;
  /** The actual tool handler */
  handler: (args: T) => Promise<R>;
}

/**
 * Attested tool returned by createAttestedTool. Contains the original
 * MCP tool definition plus the wrapped handler.
 */
export interface AttestedTool<T = any, R = any> {
  /** Tool name */
  name: string;
  /** Human-readable description */
  description: string;
  /** JSON Schema for the tool's input */
  inputSchema: Record<string, any>;
  /** Wrapped handler that attests every invocation */
  handler: (args: T) => Promise<{ result: R; receipt: any }>;
}

/**
 * Create an MCP tool definition with built-in H33 attestation.
 * Use this when you want per-tool attestation control rather than
 * wrapping the entire server with attestMCPServer.
 *
 * The returned handler wraps every call: hash input, execute, hash output,
 * attest via H33, return result + receipt.
 *
 * @param agent - A started H33Agent instance
 * @param def   - Tool definition including handler
 * @returns Tool definition with an attested handler
 *
 * @example
 * ```typescript
 * import { H33Agent } from '@h33/agent';
 * import { createAttestedTool } from '@h33/mcp';
 *
 * const agent = new H33Agent({
 *   name: 'Claims Agent',
 *   canonicalName: 'h33.agent.acme.claims.review.prod.001',
 *   tenantId: 'acme-corp',
 * });
 * await agent.start();
 *
 * const searchTool = createAttestedTool(agent, {
 *   name: 'search_database',
 *   description: 'Search the claims database',
 *   inputSchema: {
 *     type: 'object',
 *     properties: { query: { type: 'string' } },
 *     required: ['query'],
 *   },
 *   handler: async (args) => {
 *     return await db.search(args.query);
 *   },
 * });
 *
 * // Every call is attested
 * const { result, receipt } = await searchTool.handler({ query: 'open claims' });
 * console.log(receipt.verification_url);
 * ```
 */
export function createAttestedTool<T, R>(
  agent: H33Agent,
  def: AttestedToolDef<T, R>,
): AttestedTool<T, R> {
  const canonicalName = `h33.tool.mcp.${def.name}.v1`;

  const wrappedHandler = agent.tool(canonicalName, def.handler);

  return {
    name: def.name,
    description: def.description,
    inputSchema: def.inputSchema,
    handler: wrappedHandler,
  };
}
