import request from '@/utils/request'

export type MidMode = 'agent' | 'micro_flow' | 'fixed' | 'transfer'
export type SessionMode = 'BOT_ACTIVE' | 'HUMAN_ACTIVE'

export interface DialogueMessage {
  role: 'user' | 'assistant' | 'human'
  content: string
}

export interface InterruptedSegment {
  segment_id: string
  content: string
}

export interface DialogueRequest {
  session_id: string
  user_id?: string
  user_message: string
  history: DialogueMessage[]
  interrupted_segments?: InterruptedSegment[]
  feature_flags?: {
    agent_enabled?: boolean
    rollback_to_legacy?: boolean
  }
}

export interface ToolCallTrace {
  tool_name: string
  tool_type?: 'internal' | 'mcp'
  registry_version?: string
  auth_applied?: boolean
  duration_ms: number
  status: 'ok' | 'timeout' | 'error' | 'rejected'
  error_code?: string
  args_digest?: string
  result_digest?: string
  arguments?: Record<string, unknown>
  result?: unknown
}

export interface DialogueResponse {
  segments: Array<{
    segment_id: string
    text: string
    delay_after: number
  }>
  trace: {
    mode: MidMode
    intent?: string
    request_id?: string
    generation_id?: string
    guardrail_triggered?: boolean
    fallback_reason_code?: string
    react_iterations?: number
    timeout_profile?: {
      per_tool_timeout_ms?: number
      end_to_end_timeout_ms?: number
    }
    high_risk_policy_set?: string[]
    tools_used?: string[]
    tool_calls?: ToolCallTrace[]
    metrics_snapshot?: {
      task_completion_rate?: number
      slot_completion_rate?: number
      wrong_transfer_rate?: number
      no_recall_rate?: number
      avg_latency_ms?: number
    }
  }
}

export function respondDialogue(data: DialogueRequest): Promise<DialogueResponse> {
  return request({
    url: '/mid/dialogue/respond',
    method: 'post',
    data
  })
}

export function switchSessionMode(sessionId: string, mode: SessionMode, reason?: string): Promise<{ session_id: string; mode: SessionMode }> {
  return request({
    url: `/mid/sessions/${sessionId}/mode`,
    method: 'post',
    data: {
      mode,
      reason
    }
  })
}

export function reportMessages(data: {
  session_id: string
  messages: Array<{
    role: 'user' | 'assistant' | 'human' | 'system'
    content: string
    source: 'bot' | 'human' | 'channel'
    timestamp: string
    segment_id?: string
  }>
}): Promise<void> {
  return request({
    url: '/mid/messages/report',
    method: 'post',
    data
  })
}

export interface CreateShareRequest {
  title?: string
  description?: string
  expires_in_days?: number
  max_concurrent_users?: number
}

export interface ShareResponse {
  share_token: string
  share_url: string
  expires_at: string
  title?: string
  description?: string
  max_concurrent_users: number
}

export interface ShareListItem {
  share_token: string
  share_url: string
  title?: string
  description?: string
  expires_at: string
  is_active: boolean
  max_concurrent_users: number
  current_users: number
  created_at: string
}

export interface ShareListResponse {
  shares: ShareListItem[]
}

export interface SharedSessionInfo {
  session_id: string
  title?: string
  description?: string
  expires_at: string
  max_concurrent_users: number
  current_users: number
  history: DialogueMessage[]
}

export interface CreatePublicShareTokenRequest {
  tenant_id?: string
  api_key?: string
  session_id: string
  user_id?: string
  expires_in_minutes?: number
}

export interface CreatePublicShareTokenResponse {
  share_token: string
  share_url: string
  expires_at: string
}

export function createShare(sessionId: string, data: CreateShareRequest = {}): Promise<ShareResponse> {
  return request({
    url: `/mid/sessions/${sessionId}/share`,
    method: 'post',
    data
  })
}

export function createPublicShareToken(data: CreatePublicShareTokenRequest): Promise<CreatePublicShareTokenResponse> {
  return request({
    url: '/openapi/v1/share/token',
    method: 'post',
    data
  })
}

export function getSharedSession(shareToken: string): Promise<SharedSessionInfo> {
  return request({
    url: `/mid/share/${shareToken}`,
    method: 'get'
  })
}

export function listShares(sessionId: string, includeExpired = false): Promise<ShareListResponse> {
  return request({
    url: `/mid/sessions/${sessionId}/shares`,
    method: 'get',
    params: { include_expired: includeExpired }
  })
}

export function deleteShare(shareToken: string): Promise<{ success: boolean; message: string }> {
  return request({
    url: `/mid/share/${shareToken}`,
    method: 'delete'
  })
}

export function joinSharedSession(shareToken: string): Promise<SharedSessionInfo> {
  return request({
    url: `/mid/share/${shareToken}/join`,
    method: 'post'
  })
}

export function leaveSharedSession(shareToken: string): Promise<{ success: boolean; current_users: number }> {
  return request({
    url: `/mid/share/${shareToken}/leave`,
    method: 'post'
  })
}

export function sendSharedMessage(shareToken: string, userMessage: string): Promise<{ success: boolean; message: string; session_id: string }> {
  return request({
    url: `/mid/share/${shareToken}/message`,
    method: 'post',
    data: { user_message: userMessage }
  })
}

export interface CancelFlowResponse {
  success: boolean
  message: string
  session_id: string
}

export function cancelActiveFlow(sessionId: string): Promise<CancelFlowResponse> {
  return request({
    url: `/mid/sessions/${sessionId}/cancel-flow`,
    method: 'post'
  })
}
