/**
 * Terminal Telemetry - Omni-Terminal 可觀測性
 * =============================================
 * Phase 19.O - 可觀測性整合
 *
 * 追蹤 Terminal 和 GenUI 組件的:
 * - 使用者互動事件
 * - SSE 連線狀態
 * - Intent 處理時間
 * - Nuclear Key 授權行為
 *
 * 整合:
 * - Sentry: 錯誤追蹤 + 交易追蹤
 * - 自定義 Spans: 效能測量
 *
 * @see sentry.client.config.ts
 * @see ADR-031 Omni-Terminal SSE Architecture
 * @author Claude Code (首席架構師)
 * @version 1.0.0
 * @date 2026-03-28 (台北時間)
 */

import * as Sentry from '@sentry/nextjs'

// =============================================================================
// Types
// =============================================================================

export interface TerminalIntentEvent {
  /** Intent 類型 */
  intentType: string
  /** 輸入文字長度 */
  inputLength: number
  /** Session ID */
  sessionId?: string
  /** 處理時間 (ms) */
  duration?: number
  /** 是否成功 */
  success?: boolean
}

export interface SSEConnectionEvent {
  /** 連線狀態 */
  state: 'connecting' | 'connected' | 'disconnected' | 'error' | 'reconnecting'
  /** Session ID */
  sessionId?: string
  /** 錯誤訊息 */
  error?: string
  /** 重試次數 */
  retryCount?: number
}

export interface NuclearKeyEvent {
  /** 授權 ID */
  approvalId: string
  /** 風險等級 */
  riskLevel: 'low' | 'medium' | 'high' | 'critical'
  /** 操作 */
  action: 'started' | 'cancelled' | 'completed'
  /** 按住時間 (ms) */
  holdDuration?: number
  /** 是否成功 */
  success?: boolean
}

export interface GenUIRenderEvent {
  /** 組件名稱 */
  componentName: string
  /** 渲染時間 (ms) */
  renderTime?: number
  /** 是否成功 */
  success: boolean
  /** 錯誤訊息 */
  error?: string
  /** 錯誤分類碼 (Phase 19 首席架構師審查 P1 - 便於 Sentry 聚合) */
  errorCode?: 'NOT_REGISTERED' | 'DEF_NOT_FOUND' | 'ZOD_VALIDATION_FAILED' | 'LEGACY_TYPE_MISMATCH' | 'RENDER_ERROR' | 'UNKNOWN_COMPONENT'
}

// =============================================================================
// Terminal Intent Tracking
// =============================================================================

/**
 * 追蹤 Intent 提交事件
 */
export function trackIntentSubmit(event: TerminalIntentEvent): void {
  Sentry.addBreadcrumb({
    category: 'terminal.intent',
    message: `Intent submitted: ${event.intentType}`,
    level: 'info',
    data: {
      intentType: event.intentType,
      inputLength: event.inputLength,
      sessionId: event.sessionId,
    },
  })

  // 記錄到 Sentry 自定義指標
  Sentry.setMeasurement('terminal.intent.input_length', event.inputLength, 'none')
}

// =============================================================================
// Slow Query Thresholds (Phase 19 首席架構師審查 P2 改進)
// =============================================================================

/** 慢查詢臨界值 (ms) */
const SLOW_QUERY_THRESHOLDS = {
  /** 警告級別 (5 秒) */
  WARNING: 5000,
  /** 嚴重級別 (10 秒) */
  CRITICAL: 10000,
} as const

/**
 * 追蹤 Intent 完成事件
 *
 * Phase 19 首席架構師審查改進:
 * - 新增 Slow Query 監控告警
 * - 超過 5 秒警告，超過 10 秒嚴重
 */
export function trackIntentComplete(event: TerminalIntentEvent): void {
  Sentry.addBreadcrumb({
    category: 'terminal.intent',
    message: `Intent completed: ${event.intentType} (${event.success ? 'success' : 'failed'})`,
    level: event.success ? 'info' : 'warning',
    data: {
      intentType: event.intentType,
      duration: event.duration,
      success: event.success,
      sessionId: event.sessionId,
    },
  })

  if (event.duration) {
    Sentry.setMeasurement('terminal.intent.duration_ms', event.duration, 'millisecond')

    // Slow Query 監控 (Phase 19 首席架構師審查 P2)
    if (event.duration > SLOW_QUERY_THRESHOLDS.WARNING) {
      const severity = event.duration > SLOW_QUERY_THRESHOLDS.CRITICAL ? 'critical' : 'warning'

      Sentry.captureMessage(`Slow Intent Processing: ${event.intentType}`, {
        level: severity === 'critical' ? 'error' : 'warning',
        tags: {
          component: 'omni-terminal',
          slow_query: 'true',
          severity,
        },
        extra: {
          intentType: event.intentType,
          duration: event.duration,
          sessionId: event.sessionId,
          threshold: severity === 'critical'
            ? SLOW_QUERY_THRESHOLDS.CRITICAL
            : SLOW_QUERY_THRESHOLDS.WARNING,
        },
        fingerprint: ['slow-intent', event.intentType, severity],
      })
    }
  }
}

// =============================================================================
// SSE Connection Tracking
// =============================================================================

/**
 * 追蹤 SSE 連線狀態變更
 */
export function trackSSEConnection(event: SSEConnectionEvent): void {
  const level = event.state === 'error' ? 'error' : 'info'

  Sentry.addBreadcrumb({
    category: 'terminal.sse',
    message: `SSE connection: ${event.state}`,
    level,
    data: {
      state: event.state,
      sessionId: event.sessionId,
      retryCount: event.retryCount,
      error: event.error,
    },
  })

  // 錯誤時捕獲例外
  if (event.state === 'error' && event.error) {
    Sentry.captureMessage(`SSE Connection Error: ${event.error}`, {
      level: 'warning',
      tags: {
        component: 'omni-terminal',
        sse_state: event.state,
      },
      extra: {
        sessionId: event.sessionId,
        retryCount: event.retryCount,
      },
    })
  }
}

// =============================================================================
// Nuclear Key Tracking
// =============================================================================

/**
 * 追蹤 Nuclear Key 授權事件
 */
export function trackNuclearKey(event: NuclearKeyEvent): void {
  const level = event.action === 'completed' && event.success ? 'info' : 'warning'

  Sentry.addBreadcrumb({
    category: 'terminal.nuclear_key',
    message: `Nuclear Key ${event.action}: ${event.approvalId} (${event.riskLevel})`,
    level,
    data: {
      approvalId: event.approvalId,
      riskLevel: event.riskLevel,
      action: event.action,
      holdDuration: event.holdDuration,
      success: event.success,
    },
  })

  // 高風險操作完成時記錄
  if (event.action === 'completed' && (event.riskLevel === 'high' || event.riskLevel === 'critical')) {
    Sentry.captureMessage(`High-risk approval executed: ${event.approvalId}`, {
      level: 'info',
      tags: {
        component: 'nuclear-key',
        risk_level: event.riskLevel,
      },
      extra: {
        holdDuration: event.holdDuration,
        success: event.success,
      },
    })
  }

  if (event.holdDuration) {
    Sentry.setMeasurement('nuclear_key.hold_duration_ms', event.holdDuration, 'millisecond')
  }
}

// =============================================================================
// GenUI Rendering Tracking
// =============================================================================

/**
 * 追蹤 GenUI 組件渲染
 *
 * Phase 19 首席架構師審查 P1 改進:
 * - 新增 errorCode 標籤便於 Sentry 聚合分析
 * - fingerprint 分組相同類型錯誤
 */
export function trackGenUIRender(event: GenUIRenderEvent): void {
  Sentry.addBreadcrumb({
    category: 'terminal.genui',
    message: `GenUI render: ${event.componentName} (${event.success ? 'success' : 'failed'})`,
    level: event.success ? 'info' : 'error',
    data: {
      componentName: event.componentName,
      renderTime: event.renderTime,
      success: event.success,
      error: event.error,
      errorCode: event.errorCode,
    },
  })

  // 渲染失敗時捕獲 (含錯誤分類碼)
  if (!event.success && event.error) {
    Sentry.captureMessage(`GenUI render failed: ${event.componentName}`, {
      level: 'error',
      tags: {
        component: 'genui-renderer',
        genui_component: event.componentName,
        error_code: event.errorCode || 'UNKNOWN',
      },
      extra: {
        error: event.error,
        renderTime: event.renderTime,
      },
      // 按 errorCode 聚合相同類型錯誤 (Phase 19 P1)
      fingerprint: ['genui-render-failed', event.componentName, event.errorCode || 'UNKNOWN'],
    })
  }

  if (event.renderTime) {
    Sentry.setMeasurement('genui.render_time_ms', event.renderTime, 'millisecond')
  }
}

// =============================================================================
// Transaction Helpers
// =============================================================================

/**
 * 開始一個 Terminal 交易追蹤
 */
export function startTerminalTransaction(
  name: string,
  op: string = 'terminal.operation'
): ReturnType<typeof Sentry.startInactiveSpan> {
  return Sentry.startInactiveSpan({
    name,
    op,
    attributes: {
      'terminal.component': 'omni-terminal',
    },
  })
}

/**
 * 設定 Terminal 上下文標籤
 */
export function setTerminalContext(sessionId: string, intentType?: string): void {
  Sentry.setTag('terminal.session_id', sessionId)
  if (intentType) {
    Sentry.setTag('terminal.intent_type', intentType)
  }
}

/**
 * 清除 Terminal 上下文
 */
export function clearTerminalContext(): void {
  Sentry.setTag('terminal.session_id', undefined)
  Sentry.setTag('terminal.intent_type', undefined)
}
