import request from '@/utils/request'
import type { Agent, IApiStepTask, IRawPlanResponse, IRawStepTask } from '@/stores'
import {
  mockBackendAgentSelectModifyInit,
  mockBackendAgentSelectModifyAddAspect,
  type BackendAgentScoreResponse,
} from '@/layout/components/Main/TaskTemplate/TaskSyllabus/components/mock/AgentAssignmentBackendMock'
import {
  mockBackendFillAgentTaskProcess,
  type RawAgentTaskProcessResponse,
} from '@/layout/components/Main/TaskTemplate/TaskProcess/components/mock/AgentTaskProcessBackendMock'
import { mockBranchPlanOutlineAPI } from '@/layout/components/Main/TaskTemplate/TaskSyllabus/Branch/mock/branchPlanOutlineMock'
import { mockFillStepTaskAPI } from '@/layout/components/Main/TaskTemplate/TaskSyllabus/Branch/mock/fill-step-task-mock'
import {
  mockBranchTaskProcessAPI,
  type BranchAction,
} from '@/layout/components/Main/TaskTemplate/TaskSyllabus/Branch/mock/branchTaskProcessMock'

export interface ActionHistory {
  ID: string
  ActionType: string
  AgentName: string
  Description: string
  ImportantInput: string[]
  Action_Result: string
}

export type IExecuteRawResponse = {
  LogNodeType: string
  NodeId: string
  InputName_List?: string[] | null
  OutputName?: string
  content?: string
  ActionHistory: ActionHistory[]
}

export interface IFillAgentSelectionRequest {
  goal: string
  stepTask: IApiStepTask
  agents: string[]
}

class Api {
  setAgents = (data: Pick<Agent, 'Name' | 'Profile' | 'apiUrl' | 'apiKey' | 'apiModel'>[]) => {
    return request({
      url: '/setAgents',
      data,
      method: 'POST',
    })
  }

  generateBasePlan = (data: {
    goal: string
    inputs: string[]
    apiUrl?: string
    apiKey?: string
    apiModel?: string
  }) => {
    return request<unknown, IRawPlanResponse>({
      url: '/generate_basePlan',
      method: 'POST',
      data: {
        'General Goal': data.goal,
        'Initial Input Object': data.inputs,
        apiUrl: data.apiUrl,
        apiKey: data.apiKey,
        apiModel: data.apiModel,
      },
    })
  }

  executePlan = (plan: IRawPlanResponse) => {
    return request<unknown, IExecuteRawResponse[]>({
      url: '/executePlan',
      method: 'POST',
      data: {
        RehearsalLog: [],
        num_StepToRun: null,
        plan: {
          'Initial Input Object': plan['Initial Input Object'],
          'General Goal': plan['General Goal'],
          'Collaboration Process': plan['Collaboration Process']?.map((step) => ({
            StepName: step.StepName,
            TaskContent: step.TaskContent,
            InputObject_List: step.InputObject_List,
            OutputObject: step.OutputObject,
            AgentSelection: step.AgentSelection,
            Collaboration_Brief_frontEnd: step.Collaboration_Brief_frontEnd,
            TaskProcess: step.TaskProcess.map((action) => ({
              ActionType: action.ActionType,
              AgentName: action.AgentName,
              Description: action.Description,
              ID: action.ID,
              ImportantInput: action.ImportantInput,
            })),
          })),
        },
      },
    })
  }

  // 分支任务大纲
  branchPlanOutline = (data: {
    branch_Number: number
    Modification_Requirement: string
    Existing_Steps: string[]
    Baseline_Completion: number
    initialInputs: string[]
    goal: string
  }) => {
    return request<unknown, IRawPlanResponse>({
      url: '/branch_PlanOutline',
      method: 'POST',
      data: {
        branch_Number: data.branch_Number,
        Modification_Requirement: data.Modification_Requirement,
        Existing_Steps: data.Existing_Steps,
        Baseline_Completion: data.Baseline_Completion,
        'Initial Input Object': data.initialInputs,
        'General Goal': data.goal,
      },
    })
  }

  // 分支任务流程
  branchTaskProcess = (data: {
    branch_Number: number
    Modification_Requirement: string
    Existing_Steps: BranchAction[]
    Baseline_Completion: number
    stepTaskExisting: any
    goal: string
  }) => {
    return request<unknown, BranchAction[][]>({
      url: '/branch_TaskProcess',
      method: 'POST',
      data: {
        branch_Number: data.branch_Number,
        Modification_Requirement: data.Modification_Requirement,
        Existing_Steps: data.Existing_Steps,
        Baseline_Completion: data.Baseline_Completion,
        stepTaskExisting: data.stepTaskExisting,
        'General Goal': data.goal,
      },
    })
  }

  fillStepTask = async (data: { goal: string; stepTask: any }): Promise<IRawStepTask> => {
    // 后端返回格式：包含 Collaboration_Brief_FrontEnd（大写 FrontEnd）
    const response = await request<
      {
        'General Goal': string
        stepTask: any
      },
      {
        AgentSelection?: string[]
        Collaboration_Brief_FrontEnd?: {
          template: string
          data: Record<string, { text: string; color: number[] }>
        }
        InputObject_List?: string[]
        OutputObject?: string
        StepName?: string
        TaskContent?: string
        TaskProcess?: Array<{
          ID: string
          ActionType: string
          AgentName: string
          Description: string
          ImportantInput: string[]
        }>
      }
    >({
      url: '/fill_stepTask',
      method: 'POST',
      data: {
        'General Goal': data.goal,
        stepTask: data.stepTask,
      },
    })

    // 数据转换：后端的 Collaboration_Brief_FrontEnd → 前端的 Collaboration_Brief_frontEnd

    const vec2Hsl = (color: number[]): string => {
      const [h, s, l] = color
      return `hsl(${h}, ${s}%, ${l}%)`
    }

    // 转换 brief.data：后端格式 { "0": { text, color: [h,s,l] } } → 前端格式 { "0": { text, style: { background } } }
    const briefData: Record<string, { text: string; style?: Record<string, string> }> = {}
    if (response.Collaboration_Brief_FrontEnd?.data) {
      for (const [key, value] of Object.entries(response.Collaboration_Brief_FrontEnd.data)) {
        briefData[key] = {
          text: value.text,
          style: {
            background: vec2Hsl(value.color),
          },
        }
      }
    }

    // 构建前端格式的 IRawStepTask
    return {
      StepName: response.StepName || '',
      TaskContent: response.TaskContent || '',
      InputObject_List: response.InputObject_List || [],
      OutputObject: response.OutputObject || '',
      AgentSelection: response.AgentSelection || [],
      Collaboration_Brief_frontEnd: {
        template: response.Collaboration_Brief_FrontEnd?.template || '',
        data: briefData,
      },
      TaskProcess: response.TaskProcess || [],
    }
  }

  fillStepTaskTaskProcess = async (data: {
    goal: string
    stepTask: IApiStepTask
    agents: string[]
  }): Promise<IApiStepTask> => {
    // 后端返回格式: IRawStepTask
    const response = await request<
      {
        'General Goal': string
        stepTask_lackTaskProcess: {
          StepName: string
          TaskContent: string
          InputObject_List: string[]
          OutputObject: string
          AgentSelection: string[]
        }
      },
      {
        StepName?: string
        TaskContent?: string
        InputObject_List?: string[]
        OutputObject?: string
        AgentSelection?: string[]
        TaskProcess?: Array<{
          ID: string
          ActionType: string
          AgentName: string
          Description: string
          ImportantInput: string[]
        }>
        Collaboration_Brief_FrontEnd?: {
          template: string
          data: Record<string, { text: string; color: number[] }>
        }
      }
    >({
      url: '/fill_stepTask_TaskProcess',
      method: 'POST',
      data: {
        'General Goal': data.goal,
        stepTask_lackTaskProcess: {
          StepName: data.stepTask.name,
          TaskContent: data.stepTask.content,
          InputObject_List: data.stepTask.inputs,
          OutputObject: data.stepTask.output,
          AgentSelection: data.agents,
        },
      },
    })

    // 数据转换：后端格式 (IRawStepTask) → 前端格式 (IApiStepTask)
    // 注意：此转换逻辑与Mock API完全一致

    // 1. 转换颜色格式：[h, s, l] → "hsl(h, s%, l%)"
    const vec2Hsl = (color: number[]): string => {
      const [h, s, l] = color
      return `hsl(${h}, ${s}%, ${l}%)`
    }

    // 2. 转换 brief.data: { "0": { text, color: [h,s,l] } } → { "0": { text, style: { background } } }
    const briefData: Record<string, { text: string; style: { background: string } }> = {}
    if (response.Collaboration_Brief_FrontEnd?.data) {
      for (const [key, value] of Object.entries(response.Collaboration_Brief_FrontEnd.data)) {
        briefData[key] = {
          text: value.text,
          style: {
            background: vec2Hsl(value.color),
          },
        }
      }
    }

    // 3. 转换 process: { ID, ActionType, AgentName, Description, ImportantInput } → { id, type, agent, description, inputs }
    const process = (response.TaskProcess || []).map((action) => ({
      id: action.ID,
      type: action.ActionType,
      agent: action.AgentName,
      description: action.Description,
      inputs: action.ImportantInput,
    }))

    // 4. 构建前端格式的 IApiStepTask
    return {
      name: response.StepName || '',
      content: response.TaskContent || '',
      inputs: response.InputObject_List || [],
      output: response.OutputObject || '',
      agents: response.AgentSelection || [],
      brief: {
        template: response.Collaboration_Brief_FrontEnd?.template || '',
        data: briefData,
      },
      process,
    }
  }

  // 为每个智能体评分
  agentSelectModifyInit = async (data: {
    goal: string
    stepTask: any
  }): Promise<Record<string, Record<string, { reason: string; score: number }>>> => {
    // 后端返回：维度 -> agent -> { Reason, Score }
    const response = await request<
      {
        'General Goal': string
        stepTask: any
      },
      Record<string, Record<string, { Reason: string; Score: number }>>
    >({
      url: '/agentSelectModify_init',
      method: 'POST',
      data: {
        'General Goal': data.goal,
        stepTask: {
          StepName: data.stepTask.StepName || data.stepTask.name,
          TaskContent: data.stepTask.TaskContent || data.stepTask.content,
          InputObject_List: data.stepTask.InputObject_List || data.stepTask.inputs,
          OutputObject: data.stepTask.OutputObject || data.stepTask.output,
        },
      },
    })

    // 数据转换：后端格式 (维度->agent) → 前端格式 (agent->维度)
    const transformedData: Record<string, Record<string, { reason: string; score: number }>> = {}

    for (const [aspect, agents] of Object.entries(response)) {
      // aspect: 维度名称, agents: { agentName: { Reason, Score } }
      for (const [agentName, scoreInfo] of Object.entries(agents)) {
        if (!transformedData[agentName]) {
          transformedData[agentName] = {}
        }
        transformedData[agentName][aspect] = {
          reason: scoreInfo.Reason,
          score: scoreInfo.Score,
        }
      }
    }

    return transformedData
  }

  // 添加新的评估维度
  // 定义返回类型（与 Mock 数据格式一致）
  agentSelectModifyAddAspect = async (data: {
    aspectList: string[]
  }): Promise<{
    aspectName: string
    agentScores: Record<string, { score: number; reason: string }>
  }> => {
    // 后端返回：维度 -> agent -> { Reason, Score }
    const response = await request<
      {
        aspectList: string[]
      },
      Record<string, Record<string, { Reason: string; Score: number }>>
    >({
      url: '/agentSelectModify_addAspect',
      method: 'POST',
      data: {
        aspectList: data.aspectList,
      },
    })

    // 获取新添加的维度（最后一个）
    const newAspect = data.aspectList[data.aspectList.length - 1]
    if (!newAspect) {
      throw new Error('aspectList is empty')
    }

    // 提取该维度的数据：维度 -> agent -> { Reason, Score } → agent -> { score, reason }
    const newAspectAgents = response[newAspect]
    const agentScores: Record<string, { score: number; reason: string }> = {}

    if (newAspectAgents) {
      for (const [agentName, scoreInfo] of Object.entries(newAspectAgents)) {
        agentScores[agentName] = {
          score: scoreInfo.Score,
          reason: scoreInfo.Reason,
        }
      }
    }

    return {
      aspectName: newAspect,
      agentScores,
    }
  }

  // ==================== Mock API（开发阶段使用）====================
  // Mock API 使用与真实 API 相同的数据转换逻辑，确保将来切换无缝

  // Mock: 为每个智能体评分
  mockAgentSelectModifyInit = async (): Promise<
    Record<string, Record<string, { reason: string; score: number }>>
  > => {
    // 调用Mock后端数据（维度 -> agent -> { Reason, Score }）
    const response: BackendAgentScoreResponse = await mockBackendAgentSelectModifyInit()

    // 数据转换：后端格式 (维度->agent) → 前端格式 (agent->维度)
    // 注意：此转换逻辑与真实API完全一致
    const transformedData: Record<string, Record<string, { reason: string; score: number }>> = {}

    for (const [aspect, agents] of Object.entries(response)) {
      // aspect: 维度名称, agents: { agentName: { Reason, Score } }
      for (const [agentName, scoreInfo] of Object.entries(agents)) {
        if (!transformedData[agentName]) {
          transformedData[agentName] = {}
        }
        transformedData[agentName][aspect] = {
          reason: scoreInfo.Reason,
          score: scoreInfo.Score,
        }
      }
    }

    return transformedData
  }

  // Mock: 添加新的评估维度
  mockAgentSelectModifyAddAspect = async (data: {
    aspectList: string[]
  }): Promise<{
    aspectName: string
    agentScores: Record<string, { score: number; reason: string }>
  }> => {
    // 调用Mock后端数据（维度 -> agent -> { Reason, Score }）
    const response: BackendAgentScoreResponse = await mockBackendAgentSelectModifyAddAspect(
      data.aspectList,
    )

    // 获取新添加的维度（最后一个）
    const newAspect = data.aspectList[data.aspectList.length - 1]
    if (!newAspect) {
      throw new Error('aspectList is empty')
    }

    // 提取该维度的数据：维度 -> agent -> { Reason, Score } → agent -> { score, reason }
    // 注意：此转换逻辑与真实API完全一致
    const newAspectAgents = response[newAspect]
    const agentScores: Record<string, { score: number; reason: string }> = {}

    if (newAspectAgents) {
      for (const [agentName, scoreInfo] of Object.entries(newAspectAgents)) {
        agentScores[agentName] = {
          score: scoreInfo.Score,
          reason: scoreInfo.Reason,
        }
      }
    }

    return {
      aspectName: newAspect,
      agentScores,
    }
  }

  // Mock: 填充智能体任务流程
  mockFillStepTaskTaskProcess = async (data: {
    goal: string
    stepTask: IApiStepTask
    agents: string[]
  }): Promise<IApiStepTask> => {
    // 调用Mock后端数据（后端原始格式）
    const response: RawAgentTaskProcessResponse = await mockBackendFillAgentTaskProcess(
      data.goal,
      data.stepTask,
      data.agents,
    )

    // 数据转换：后端格式 → 前端格式
    // 注意：此转换逻辑与真实API完全一致

    // 1. 转换颜色格式：[h, s, l] → "hsl(h, s%, l%)"
    const vec2Hsl = (color: number[]): string => {
      const [h, s, l] = color
      return `hsl(${h}, ${s}%, ${l}%)`
    }

    // 2. 转换 brief.data: { "0": { text, color: [h,s,l] } } → { "0": { text, style: { background } } }
    const briefData: Record<string, { text: string; style: { background: string } }> = {}
    if (response.Collaboration_Brief_frontEnd?.data) {
      for (const [key, value] of Object.entries(response.Collaboration_Brief_frontEnd.data)) {
        briefData[key] = {
          text: value.text,
          style: {
            background: vec2Hsl(value.color),
          },
        }
      }
    }

    // 3. 转换 process: { ID, ActionType, AgentName, Description, ImportantInput } → { id, type, agent, description, inputs }
    const process = (response.TaskProcess || []).map((action) => ({
      id: action.ID,
      type: action.ActionType,
      agent: action.AgentName,
      description: action.Description,
      inputs: action.ImportantInput,
    }))

    // 4. 构建前端格式的 IApiStepTask
    return {
      name: response.StepName || '',
      content: response.TaskContent || '',
      inputs: response.InputObject_List || [],
      output: response.OutputObject || '',
      agents: response.AgentSelection || [],
      brief: {
        template: response.Collaboration_Brief_frontEnd?.template || '',
        data: briefData,
      },
      process,
    }
  }

  // Mock: 分支任务大纲
  mockBranchPlanOutline = async (data: {
    branch_Number: number
    Modification_Requirement: string
    Existing_Steps: string[]
    Baseline_Completion: number
    initialInputs: string[]
    goal: string
  }): Promise<IRawPlanResponse> => {
    // 直接调用 Mock API（已经返回 IRawPlanResponse 格式）
    const response = await mockBranchPlanOutlineAPI({
      branch_Number: data.branch_Number,
      Modification_Requirement: data.Modification_Requirement,
      Existing_Steps: data.Existing_Steps,
      Baseline_Completion: data.Baseline_Completion,
      InitialObject_List: data.initialInputs,
      General_Goal: data.goal,
    })

    return response
  }

  // Mock: 填充任务流程
  mockFillStepTask = async (data: { goal: string; stepTask: any }): Promise<any> => {
    // 直接调用 Mock API（已经返回 IRawStepTask 格式）
    const response = await mockFillStepTaskAPI({
      General_Goal: data.goal,
      stepTask: data.stepTask,
    })

    return response
  }

  // Mock: 分支任务流程
  mockBranchTaskProcess = async (data: {
    branch_Number: number
    Modification_Requirement: string
    Existing_Steps: BranchAction[]
    Baseline_Completion: number
    stepTaskExisting: any
    goal: string
  }): Promise<BranchAction[][]> => {
    // 直接调用 Mock API（已经返回 BranchAction[][] 格式，与后端完全一致）
    const response = await mockBranchTaskProcessAPI({
      branch_Number: data.branch_Number,
      Modification_Requirement: data.Modification_Requirement,
      Existing_Steps: data.Existing_Steps,
      Baseline_Completion: data.Baseline_Completion,
      stepTaskExisting: data.stepTaskExisting,
      General_Goal: data.goal,
    })

    return response
  }
}

export default new Api()
