import request from '@/utils/request'

export interface Session {
  sessionId: string
  tenantId: string
  messageCount: number
  status: string
  channelType: string
  startTime: string
}

export interface SessionDetail {
  sessionId: string
  messages: Array<{
    role: string
    content: string
    timestamp: string
  }>
  trace?: {
    retrieval?: Array<{
      score: number
      source?: string
      content: string
    }>
    tools?: Array<Record<string, unknown>>
  }
}

export interface SessionListResponse {
  data: Session[]
  total: number
}

export function listSessions(params?: { page?: number; pageSize?: number; status?: string }): Promise<SessionListResponse> {
  return request({
    url: '/admin/sessions',
    method: 'get',
    params
  })
}

export function getSessionDetail(sessionId: string): Promise<SessionDetail> {
  return request({
    url: `/admin/sessions/${sessionId}`,
    method: 'get'
  })
}

export interface IntentRuleTestRequest {
  message: string
}

export interface IntentRuleTestResult {
  ruleId: string
  ruleName: string
  results: IntentRuleTestCase[]
  summary: {
    totalTests: number
    matchedCount: number
    matchRate: number
  }
}

export interface IntentRuleTestCase {
  message: string
  matched: boolean
  matchedKeywords: string[]
  matchedPatterns: string[]
  matchType: string | null
  priority: number
  priorityRank: number
  conflictRules: ConflictRule[]
  reason: string | null
}

export interface ConflictRule {
  ruleId: string
  ruleName: string
  priority: number
  reason: string
}

export interface IntentRuleStatsResponse {
  totalHits: number
  totalConversations: number
  hitRate: number
  rules: IntentRuleStatItem[]
}

export interface IntentRuleStatItem {
  ruleId: string
  ruleName: string
  hitCount: number
  hitRate: number
  avgResponseTime: number
  lastHitTime: string | null
  responseType: string
}

export interface IntentRuleHitsResponse {
  records: IntentRuleHitRecord[]
  total: number
  page: number
  pageSize: number
}

export interface IntentRuleHitRecord {
  conversationId: string
  sessionId: string
  userMessage: string
  matchedKeywords: string[]
  matchedPatterns: string[]
  responseType: string
  executionResult: string
  hitTime: string
}

export interface PromptPreviewRequest {
  variables?: Record<string, string>
  sampleHistory?: Array<{ role: string; content: string }>
  sampleMessage?: string
}

export interface PromptPreviewResponse {
  templateId: string
  templateName: string
  version: number
  rawContent: string
  variables: Array<{ name: string; value: string }>
  renderedContent: string
  estimatedTokens: number
  tokenCount: {
    systemPrompt: number
    history: number
    currentMessage: number
    total: number
  }
  warnings: string[]
}

export interface PromptTemplateStatsResponse {
  totalUsage: number
  templates: PromptTemplateStatItem[]
  sceneBreakdown: Record<string, number>
}

export interface PromptTemplateStatItem {
  templateId: string
  templateName: string
  scene: string
  usageCount: number
  avgTokens: number
  avgPromptTokens: number
  avgCompletionTokens: number
  lastUsedTime: string | null
}

export interface FlowStatsResponse {
  totalActivations: number
  totalCompletions: number
  completionRate: number
  flows: FlowStatItem[]
}

export interface FlowStatItem {
  flowId: string
  flowName: string
  activationCount: number
  completionCount: number
  completionRate: number
  avgDuration: number
  avgStepsCompleted: number
  dropOffPoints: DropOffPoint[]
  lastActivatedAt: string | null
}

export interface DropOffPoint {
  stepNo: number
  dropOffCount: number
  dropOffRate: number
}

export interface FlowExecutionsResponse {
  data: FlowExecutionRecord[]
  page: number
  pageSize: number
  total: number
}

export interface FlowExecutionRecord {
  instanceId: string
  sessionId: string
  flowId: string
  flowName: string
  currentStep: number
  totalSteps: number
  status: string
  startedAt: string
  updatedAt: string
  completedAt: string | null
}

export interface GuardrailStatsResponse {
  totalBlocks: number
  totalTriggers: number
  blockRate: number
  words: GuardrailWordStats[]
  categoryBreakdown: Record<string, number>
}

export interface GuardrailWordStats {
  wordId: string
  word: string
  category: string
  strategy: string
  hitCount: number
  blockCount: number
  lastHitAt: string | null
}

export interface GuardrailBlocksResponse {
  data: GuardrailBlockRecord[]
  page: number
  pageSize: number
  total: number
}

export interface GuardrailBlockRecord {
  recordId: string
  sessionId: string
  originalText: string
  filteredText: string
  strategy: string
  blockedAt: string
}

export function testIntentRule(ruleId: string, data: IntentRuleTestRequest): Promise<IntentRuleTestResult> {
  return request({
    url: `/admin/intent-rules/${ruleId}/test`,
    method: 'post',
    data
  })
}

export function getIntentRuleStats(params?: {
  startDate?: string
  endDate?: string
  responseType?: string
}): Promise<IntentRuleStatsResponse> {
  return request({
    url: '/admin/monitoring/intent-rules',
    method: 'get',
    params
  })
}

export function getIntentRuleHits(
  ruleId: string,
  params?: { page?: number; pageSize?: number }
): Promise<IntentRuleHitsResponse> {
  return request({
    url: `/admin/monitoring/intent-rules/${ruleId}/hits`,
    method: 'get',
    params
  })
}

export function previewPromptTemplate(
  tplId: string,
  data: PromptPreviewRequest
): Promise<PromptPreviewResponse> {
  return request({
    url: `/admin/prompt-templates/${tplId}/preview`,
    method: 'post',
    data
  })
}

export function getPromptTemplateStats(params?: {
  scene?: string
  startDate?: string
  endDate?: string
}): Promise<PromptTemplateStatsResponse> {
  return request({
    url: '/admin/monitoring/prompt-templates',
    method: 'get',
    params
  })
}

export function getFlowStats(params?: {
  startDate?: string
  endDate?: string
}): Promise<FlowStatsResponse> {
  return request({
    url: '/admin/monitoring/script-flows',
    method: 'get',
    params
  })
}

export function getFlowExecutions(
  flowId: string,
  params?: { page?: number; pageSize?: number }
): Promise<FlowExecutionsResponse> {
  return request({
    url: `/admin/monitoring/script-flows/${flowId}/executions`,
    method: 'get',
    params
  })
}

export function getGuardrailStats(params?: {
  category?: string
}): Promise<GuardrailStatsResponse> {
  return request({
    url: '/admin/monitoring/guardrails',
    method: 'get',
    params
  })
}

export function getGuardrailBlocks(
  wordId: string,
  params?: { page?: number; pageSize?: number }
): Promise<GuardrailBlocksResponse> {
  return request({
    url: `/admin/monitoring/guardrails/${wordId}/blocks`,
    method: 'get',
    params
  })
}

export interface ConversationItem {
  id: string
  sessionId: string
  userMessage: string
  aiReply: string | null
  hasFlow: boolean
  hasGuardrail: boolean
  createdAt: string
}

export interface ConversationListResponse {
  data: ConversationItem[]
  page: number
  pageSize: number
  total: number
}

export interface ConversationDetail {
  conversationId: string
  sessionId: string
  userMessage: string
  aiReply: string | null
  triggeredRules: Array<{
    id: string
    name: string
    responseType: string
  }>
  usedTemplate: {
    id: string
    name: string
  } | null
  usedFlow: {
    id: string
    flowId: string
    status: string
    currentStep: number
  } | null
  executionTimeMs: number | null
  confidence: number | null
  shouldTransfer: boolean
  guardrailTriggered: boolean
  guardrailWords: string[] | null
  executionSteps: Array<{
    step: number
    name: string
    status: string
    duration_ms: number
    input?: Record<string, any>
    output?: Record<string, any>
    error?: string
  }> | null
  createdAt: string
}

export interface ExportTaskResponse {
  taskId: string
  status: string
  format: string
  createdAt: string
  fileName?: string
  fileSize?: number
  totalRows?: number
  completedAt?: string
  errorMessage?: string
}

export interface ExportRequest {
  format?: 'json' | 'csv'
  session_id?: string
  start_date?: string
  end_date?: string
}

export function listConversations(params?: {
  session_id?: string
  start_date?: string
  end_date?: string
  has_flow?: boolean
  has_guardrail?: boolean
  page?: number
  pageSize?: number
}): Promise<ConversationListResponse> {
  return request({
    url: '/admin/monitoring/conversations',
    method: 'get',
    params
  })
}

export function getConversationDetail(messageId: string): Promise<ConversationDetail> {
  return request({
    url: `/admin/monitoring/conversations/${messageId}`,
    method: 'get'
  })
}

export function createExportTask(data: ExportRequest): Promise<ExportTaskResponse> {
  return request({
    url: '/admin/monitoring/conversations/export',
    method: 'post',
    data
  })
}

export function getExportStatus(taskId: string): Promise<ExportTaskResponse> {
  return request({
    url: `/admin/monitoring/conversations/export/${taskId}`,
    method: 'get'
  })
}

export function getExportDownloadUrl(taskId: string): string {
  return `/admin/monitoring/conversations/export/${taskId}/download`
}
