/**
 * Doctor Tools - Diagnostic and repair operations
 *
 * Implements T-213: doctor.*
 * Wraps DoctorService (P8). Stub acceptable in P2.
 *
 * @module packages/runtime/src/tools/doctor
 */

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

export const doctor_check: ToolDefinition = {
  name: 'doctor.check',
  category: 'doctor',
  description: 'Run diagnostic checks',
  input_schema: {
    type: 'object',
    properties: {
      scope: { type: 'string', enum: ['all', 'runtime', 'storage', 'project', 'permissions'], default: 'all' }
    }
  },
  permissions: { read: true, write: false, network: false },
  streaming: false
}

export const doctor_fix: ToolDefinition = {
  name: 'doctor.fix',
  category: 'doctor',
  description: 'Attempt to fix issues',
  input_schema: {
    type: 'object',
    properties: {
      issue_id: { type: 'string', description: 'Issue ID to fix' },
      dry_run: { type: 'boolean', default: false, description: 'Show what would be done without doing it' }
    },
    required: ['issue_id']
  },
  permissions: { read: false, write: true, network: false },
  streaming: false
}

// Stub executor - wraps DoctorService (P8)
export function createDoctorExecutor() {
  return {
    'doctor.check': async (call: ToolCall): Promise<ToolResultEnvelope> => {
      const { scope = 'all' } = call.arguments as { scope?: string }
      // Stub: would call DoctorService.run_diagnostics()
      return create_result(call.id, 'doctor.check', 'text', {
        scope,
        issues_found: 0,
        status: 'healthy',
        message: 'Diagnostic check complete (stub - P8 implementation pending)'
      })
    },

    'doctor.fix': async (call: ToolCall): Promise<ToolResultEnvelope> => {
      const { issue_id, dry_run = false } = call.arguments as { issue_id: string; dry_run?: boolean }
      // Stub: would call DoctorService.fix_issue()
      return create_result(call.id, 'doctor.fix', 'text', {
        issue_id,
        dry_run,
        action: dry_run ? 'would_fix' : 'fixed',
        message: `Issue ${issue_id} ${dry_run ? 'would be' : 'was'} fixed (stub - P8 implementation 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 } }
}