/**
 * Role integration wiring — T-705
 * Connects DebuggerRole↔DebugKnowledgeStore and ExperienceMinerRole↔LearnedMemoryStore
 * per DD §19.5 sequences.
 *
 * @module packages/runtime/src/agents/wiring
 */

import { DebugKnowledgeStore } from '../knowledge/DebugKnowledgeStore.js'
import { LearnedMemoryStore } from '../knowledge/LearnedMemoryStore.js'
import { eventIngestor } from '../events/EventIngestor.js'

export interface KnowledgeWiring {
  debug_store: DebugKnowledgeStore
  memory_store: LearnedMemoryStore
}

/**
 * Wire debug-knowledge-capture sequence (§19.5):
 * DebuggerRole captures error → inserts into DebugKnowledgeStore → outbox emits debug.record.created
 */
export function createKnowledgeWiring(project_root: string): KnowledgeWiring {
  const debug_store = new DebugKnowledgeStore(project_root)
  const memory_store = new LearnedMemoryStore(project_root)

  debug_store.open()
  memory_store.open()

  return { debug_store, memory_store }
}

/**
 * Handle a debug capture from DebuggerRole.
 * INV-2: External write first → then emit debug.record.created via outbox.
 * Fields aligned with DebugRecord (db-schema-v1 §20.1) after the §20 schema refactor.
 */
export async function capture_debug_record(
  store: DebugKnowledgeStore,
  record: {
    id: string
    failure_signature: string
    task_id: string
    summary: string
    root_cause?: string
    fix_ref?: string
    evidence_json?: string
    verification_json?: string
    metadata_json?: string
  }
): Promise<void> {
  const now = new Date().toISOString()
  store.insert({
    id: record.id,
    failure_signature: record.failure_signature,
    task_id: record.task_id,
    summary: record.summary,
    root_cause: record.root_cause,
    fix_ref: record.fix_ref,
    evidence_json: record.evidence_json,
    verification_json: record.verification_json,
    created_at: now,
    updated_at: now,
    metadata_json: record.metadata_json,
  })
  // INV-2: emit debug.record.created (durable) via EventIngestor AFTER external write
  await eventIngestor.ingest({
    id: record.id,
    type: 'debug.record.created',
    version: 1,
    session_id: record.task_id,
    project_id: '',
    timestamp: now,
    source: { kind: 'agent', agent_type: 'debugger' },
    route: ['knowledge', 'debug'],
    payload: {
      debug_record_id: record.id,
      task_id: record.task_id,
      failure_signature: record.failure_signature,
      summary: record.summary,
      evidence_refs: [],
      verification_refs: [],
    }
  })
}

/**
 * Handle experience mining promotion.
 * INV-2: External write first → then emit memory.promoted via outbox.
 * Fields aligned with MemoryEntry (db-schema-v1 §20.2) after the §20 schema refactor.
 */
export async function promote_memory_entry(
  store: LearnedMemoryStore,
  entry: {
    id: string
    memory_type: 'project_rule' | 'toolchain_rule' | 'skill_update' | 'debug_experience'
    summary: string
    content: string
    source_entity_type?: string
    source_entity_id?: string
    metadata_json?: string
  }
): Promise<void> {
  const now = new Date().toISOString()
  store.insert({
    id: entry.id,
    memory_type: entry.memory_type,
    summary: entry.summary,
    content: entry.content,
    source_entity_type: entry.source_entity_type,
    source_entity_id: entry.source_entity_id,
    status: 'candidate',
    created_at: now,
    updated_at: now,
    metadata_json: entry.metadata_json,
  })
  // INV-2: emit memory.promoted (durable) via EventIngestor AFTER external write
  await eventIngestor.ingest({
    id: entry.id,
    type: 'memory.promoted',
    version: 1,
    session_id: entry.source_entity_id || '',
    project_id: '',
    timestamp: now,
    source: { kind: 'agent', agent_type: 'experience_miner' },
    route: ['knowledge', 'memory'],
    payload: {
      candidate_id: entry.id,
      target_ref: entry.source_entity_type || '',
      promoted_by: 'experience_miner',
      summary: entry.summary,
    }
  })
}
