/**
 * 陪练功能API
 */
import { http } from '@/utils/http'
import type {
  GetScenesParams,
  StartPracticeParams,
  InterruptPracticeParams,
  PracticeScene,
  PaginatedResponse,
  ResponseModel
} from '@/types/practice'

/**
 * 陪练API
 */
export const practiceApi = {
  /**
   * 获取Coze OAuth Token（用于前端直连WebSocket）
   */
  getCozeToken(): Promise<ResponseModel<{ token: string }>> {
    return http.get('/api/v1/practice/coze-token')
  },

  /**
   * 获取可用场景列表
   */
  getScenes(params: GetScenesParams): Promise<ResponseModel<PaginatedResponse<PracticeScene>>> {
    return http.get('/api/v1/practice/scenes', { params })
  },

  /**
   * 获取场景详情
   */
  getSceneDetail(id: number): Promise<ResponseModel<PracticeScene>> {
    return http.get(`/api/v1/practice/scenes/${id}`)
  },

  /**
   * 开始陪练对话（SSE流式）
   * 
   * ⚠️ 注意：此方法返回ReadableStream，不能使用普通的request封装
   * 必须使用原生fetch处理SSE
   */
  startPractice(params: StartPracticeParams): Promise<ReadableStream> {
    const token = localStorage.getItem('access_token')
    // 生产环境使用当前域名，开发环境使用空字符串（走代理）
    const baseURL = (import.meta.env.DEV || import.meta.env.VITE_APP_ENV === 'development') 
      ? '' 
      : window.location.origin
    
    return fetch(`${baseURL}/api/v1/practice/start`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify(params)
    }).then(response => {
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }
      if (!response.body) {
        throw new Error('Response body is null')
      }
      return response.body
    })
  },

  /**
   * 创建对话
   * 
   * ⚠️ 重要：必须先创建conversation才能续接对话
   */
  createConversation(): Promise<ResponseModel<{ conversation_id: string }>> {
    return http.post('/api/v1/practice/conversation/create')
  },

  /**
   * 中断对话
   */
  interruptPractice(params: InterruptPracticeParams): Promise<ResponseModel> {
    return http.post('/api/v1/practice/interrupt', params)
  },

  /**
   * 从课程提取陪练场景（通过Dify工作流）
   * 
   * @param data 包含course_id的请求数据
   * @returns Promise 包含提取的场景数据
   */
  extractScene(data: { course_id: number }): Promise<ResponseModel<{
    scene: {
      name: string
      description: string
      type: string
      difficulty: string
      background: string
      ai_role: string
      objectives: string[]
      keywords: string[]
    }
    workflow_run_id: string
    task_id: string
  }>> {
    return http.post('/api/v1/practice/extract-scene', data)
  },

  /**
   * 创建陪练会话
   */
  createSession(data: {
    scene_id?: number
    scene_name: string
    scene_type?: string
    conversation_id?: string
  }): Promise<ResponseModel<{
    session_id: string
    user_id: number
    start_time: string
  }>> {
    return http.post('/api/v1/practice/sessions/create', data)
  },

  /**
   * 保存对话记录
   */
  saveDialogue(data: {
    session_id: string
    speaker: string
    content: string
    sequence: number
  }): Promise<ResponseModel> {
    return http.post('/api/v1/practice/dialogues/save', data)
  },

  /**
   * 结束陪练会话
   */
  endSession(sessionId: string): Promise<ResponseModel> {
    return http.post(`/api/v1/practice/sessions/${sessionId}/end`)
  },

  /**
   * 生成陪练分析报告（调用Dify）
   */
  analyzePractice(sessionId: string): Promise<ResponseModel<{
    session_id: string
    total_score: number
    workflow_run_id: string
  }>> {
    return http.post(`/api/v1/practice/sessions/${sessionId}/analyze`)
  },

  /**
   * 获取陪练分析报告详情
   */
  getPracticeReport(sessionId: string): Promise<ResponseModel<any>> {
    return http.get(`/api/v1/practice/reports/${sessionId}`)
  },

  /**
   * 获取陪练记录列表
   */
  getPracticeSessions(params: {
    page?: number
    size?: number
    keyword?: string
    scene_type?: string
    start_date?: string
    end_date?: string
    min_score?: number
    max_score?: number
  }): Promise<ResponseModel<any>> {
    return http.get('/api/v1/practice/sessions/list', { params })
  },

  /**
   * 获取陪练统计数据
   */
  getPracticeStats(): Promise<ResponseModel<{
    total_count: number
    avg_score: number
    total_duration_hours: number
    month_improvement: number
  }>> {
    return http.get('/api/v1/practice/stats')
  }
}

