/**
 * Create Expert — Recording Helpers
 *
 * Memory and outcome store recording for expert creation.
 * Best-effort — never fails the tool.
 *
 * @module mcp/tools/create-expert-recording
 * (Source: Issue #1174 — Add observability to dark MCP tools)
 */

import {
  createLogger,
  getErrorMessage,
  getTimeProvider,
  getRandomProvider,
} from '../../core/index.js';
import { getToolMemory } from './tool-memory.js';
import {
  getOutcomeStore,
  categorizeOutcomeErrorMessage,
} from '../../orchestration/outcomes/index.js';
import { DEFAULT_CLI } from '../../config/model-capabilities-types.js';
import type { TaskCategory } from '../../config/task-specialization-types.js';
import { ROLE_TO_TASK_CATEGORY } from './create-expert-routing.js';

const logger = createLogger({ tool: 'create-expert' });

/** Records a successful expert creation to session memory. */
export function recordExpertCreated(role: string, expertId: string): void {
  try {
    const memory = getToolMemory();
    memory.recordTask({
      approach: `Created ${role} expert (${expertId})`,
      challenges: [],
      durationMs: 0,
    });
    memory.recordLearning({
      pattern: `Expert created: ${role}`,
      context: `expertId=${expertId}`,
      confidence: 0.9,
      source: 'manual',
    });
  } catch (error: unknown) {
    logger.warn('Failed to record expert creation', { error: getErrorMessage(error) });
  }
}

/** Records a failed expert creation to session memory. */
export function recordExpertError(role: string, errorMessage: string): void {
  try {
    const memory = getToolMemory();
    memory.recordError({
      error: `Expert creation failed for ${role}: ${errorMessage.slice(0, 150)}`,
      solution: 'Check adapter availability and role validity',
      filePattern: 'mcp/tools/create-expert',
    });
  } catch (error: unknown) {
    logger.warn('Failed to record expert error', { error: getErrorMessage(error) });
  }
}

/** Resolves expert role to task category for accurate outcome attribution. */
function resolveCategory(role: string): TaskCategory {
  return ROLE_TO_TASK_CATEGORY[role] ?? 'code_generation';
}

/** Records expert creation outcome for adaptive routing. */
export function recordExpertOutcome(
  role: string,
  success: boolean,
  durationMs: number,
  error?: string
): void {
  try {
    const store = getOutcomeStore();
    const errorMsg = error ?? 'expert creation failed';
    store.append({
      id: `expert-${String(getTimeProvider().now())}-${getRandomProvider().random().toString(36).slice(2, 8)}`,
      cli: DEFAULT_CLI,
      category: resolveCategory(role),
      model: 'expert',
      success,
      durationMs,
      timestamp: new Date().toISOString(),
      source: 'manual',
      ...(!success
        ? {
            failureCategory: categorizeOutcomeErrorMessage(errorMsg),
            errorMessage: errorMsg.slice(0, 500),
          }
        : {}),
    });
  } catch (error: unknown) {
    logger.debug('Best-effort expert outcome recording failed', { error: getErrorMessage(error) });
  }
}
