import request from '@/utils/request'

export interface FlowExecutionRequest {
  message: string
  session_id?: string
  user_id?: string
  enable_flow?: boolean
  enable_intent?: boolean
  enable_rag?: boolean
  enable_guardrail?: boolean
  enable_memory?: boolean
  compare_mode?: boolean
}

export interface FlowExecutionStep {
  step: number
  name: string
  status: 'success' | 'failed' | 'skipped'
  duration_ms: number
  input?: Record<string, any>
  output?: Record<string, any>
  error?: string
}

export interface FlowExecutionResponse {
  test_id: string
  session_id: string
  status: string
  steps: FlowExecutionStep[]
  final_response: {
    reply: string
    confidence: number | null
    should_transfer: boolean
    sources?: any[]
  } | null
  total_duration_ms: number
  created_at: string
}

export interface FlowTestRecord {
  testId: string
  sessionId: string
  status: string
  stepCount: number
  totalDurationMs: number
  createdAt: string
}

export interface FlowTestListResponse {
  data: FlowTestRecord[]
  page: number
  pageSize: number
  total: number
}

export interface CompareRequest {
  message: string
  baseline_config?: Record<string, any>
  test_config?: Record<string, any>
}

export interface CompareResult {
  baseline: {
    sessionId: string
    reply: string
    confidence: number | null
    durationMs: number
    steps: FlowExecutionStep[]
  }
  test: {
    sessionId: string
    reply: string
    confidence: number | null
    durationMs: number
    steps: FlowExecutionStep[]
  }
  comparison: {
    durationDiffMs: number
    confidenceDiff: number
  }
}

export function executeFlowTest(data: FlowExecutionRequest): Promise<FlowExecutionResponse> {
  return request({
    url: '/admin/test/flow-execution',
    method: 'post',
    data
  })
}

export function getFlowTestResult(testId: string): Promise<FlowExecutionResponse> {
  return request({
    url: `/admin/test/flow-execution/${testId}`,
    method: 'get'
  })
}

export function listFlowTests(params?: {
  session_id?: string
  status?: string
  page?: number
  pageSize?: number
}): Promise<FlowTestListResponse> {
  return request({
    url: '/admin/test/flow-executions',
    method: 'get',
    params
  })
}

export function compareFlowTest(data: CompareRequest): Promise<CompareResult> {
  return request({
    url: '/admin/test/compare',
    method: 'post',
    data
  })
}
