/**
 * Permission Tools - Permission prompt resolution plumbing
 *
 * Implements T-212: permission.prompt.requested/resolved events
 *
 * @module packages/runtime/src/tools/permission
 */

import type { ToolDefinition, ToolCall, ToolResultEnvelope, ISOTimeString } from '@aircoding/contracts'

export const permission_check: ToolDefinition = {
  name: 'permission.check',
  category: 'permission',
  description: 'Check permission for a tool call',
  input_schema: {
    type: 'object',
    properties: {
      tool_name: { type: 'string', description: 'Tool name to check' },
      arguments: { type: 'object', description: 'Tool arguments' }
    },
    required: ['tool_name']
  },
  permissions: { read: true, write: false, network: false },
  streaming: false
}

export const permission_prompt: ToolDefinition = {
  name: 'permission.prompt',
  category: 'permission',
  description: 'Request user permission for an action',
  input_schema: {
    type: 'object',
    properties: {
      tool_name: { type: 'string', description: 'Tool name' },
      arguments: { type: 'object', description: 'Tool arguments' },
      reason: { type: 'string', description: 'Why permission is needed' }
    },
    required: ['tool_name', 'reason']
  },
  permissions: { read: false, write: true, network: false },
  streaming: false
}

// Stub executor - emits permission.prompt.requested/resolved events
export function createPermissionExecutor() {
  return {
    'permission.check': async (call: ToolCall): Promise<ToolResultEnvelope> => {
      const { tool_name, arguments: args } = call.arguments as { tool_name: string; arguments?: Record<string, unknown> }
      // Stub: would call PermissionEngine.evaluate()
      return create_result(call.id, 'permission.check', 'text', {
        tool_name,
        action: 'allow',
        reason: 'permission check passed (stub)',
        requires_confirmation: false
      })
    },

    'permission.prompt': async (call: ToolCall): Promise<ToolResultEnvelope> => {
      const { tool_name, reason } = call.arguments as { tool_name: string; reason: string }
      // Stub: emits permission.prompt.requested, waits for resolution
      return create_result(call.id, 'permission.prompt', 'text', {
        tool_name,
        reason,
        status: 'pending',
        message: 'Permission prompt emitted (stub - UI integration pending)'
      })
    }
  }
}

function create_result(call_id: string, tool_name: string, type: 'text' | 'error', content: Record<string, unknown>): ToolResultEnvelope {
  return { call_id, tool_name, type, content, metadata: { timestamp: new Date().toISOString() as ISOTimeString } }
}