/**
 * ArchitectureDesigner - Architecture review gate
 *
 * Implements DD §14.2 + sequence §19.4.
 * INV-3: doc writes via ToolRegistry+PermissionEngine (no direct fs/shell).
 *
 * @module packages/runtime/src/agents/architecture/ArchitectureDesigner
 */

export type ArchitectureResult = 'silent_continue' | 'requires_user_confirmation' | 'requires_replan' | 'reject_or_escalate'

export interface ArchitectureImpact {
  result: ArchitectureResult
  affected_components: string[]
  change_summary: string
  risks: string[]
  requires_replan: boolean
}

export class ArchitectureDesigner {
  /**
   * Assess the architectural impact of a proposed change.
   */
  assess_impact(change: { description: string; files: string[] }): ArchitectureImpact {
    // Analyze which components are affected
    const affected = this.identify_affected_components(change.files)

    // Determine result class
    const risk_level = this.evaluate_risk(change, affected)

    const impact: ArchitectureImpact = {
      result: 'silent_continue',
      affected_components: affected,
      change_summary: change.description,
      risks: [],
      requires_replan: false
    }

    if (risk_level >= 4) {
      impact.result = 'reject_or_escalate'
      impact.risks.push('High architectural risk')
    } else if (risk_level >= 3) {
      impact.result = 'requires_user_confirmation'
      impact.risks.push('Moderate impact on architecture')
    } else if (risk_level >= 2) {
      impact.result = 'requires_replan'
      impact.requires_replan = true
    }

    return impact
  }

  /**
   * Update architecture documentation (only if confirmed).
   * TODO(P7): Emit architecture.plan.updated event via EventIngestor.
   */
  async update_architecture_docs(impact: ArchitectureImpact): Promise<void> {
    // STUB: Only write docs if confirmed and impact is not reject
    if (impact.result === 'reject_or_escalate') return

    // INV-3: Uses ToolRegistry for file writes (not yet wired)
  }

  private identify_affected_components(files: string[]): string[] {
    const components: string[] = []
    for (const file of files) {
      if (file.includes('contracts')) components.push('contracts')
      if (file.includes('runtime')) components.push('runtime')
      if (file.includes('workers')) components.push('workers')
      if (file.includes('llm')) components.push('llm')
      if (file.includes('toolchain')) components.push('toolchain')
      if (file.includes('tui')) components.push('tui')
    }
    return [...new Set(components)]
  }

  private evaluate_risk(change: { description: string; files: string[] }, affected: string[]): number {
    let risk = 0
    if (affected.includes('contracts')) risk += 3 // Contract changes are high risk
    if (affected.includes('runtime')) risk += 2
    if (change.files.length > 10) risk += 1
    if (/deprecat|break|remove/.test(change.description.toLowerCase())) risk += 2
    return risk
  }
}
