import { getToolQuestionPairFromRow, resolveSubmitQuestionToolPair } from '@/lib/toolRoleRecordTypes'
import type { ToolListRow } from '@/types/toolList'

/**
 * 工作流提问参数：首次使用列表项的 userRole 首段（或行上 recordType）；
 * 之后各次提问使用接口流式返回中最后一次带上的 toolId / recordType。
 */
const STORAGE_KEY = 'workflowLastToolPair'
/** 本次点击会话写入的「列表第 0 项」快照，供 Chat 首次提问在流式返回前读取 */
const SEED_KEY = 'workflowRequestSeedPair'

export function clearWorkflowLastToolPair(): void {
  try {
    sessionStorage.removeItem(STORAGE_KEY)
  }
  catch {
    // ignore
  }
}

export function setWorkflowRequestSeedPair(toolId: string, recordType: string): void {
  const tid = toolId?.trim?.() ?? ''
  const rt = recordType?.trim?.() ?? ''
  if (!tid || !rt)
    return
  try {
    sessionStorage.setItem(SEED_KEY, JSON.stringify({ toolId: tid, recordType: rt }))
  }
  catch {
    // ignore
  }
}

export function getWorkflowRequestSeedPair(): { toolId: string, recordType: string } | null {
  try {
    const raw = sessionStorage.getItem(SEED_KEY)
    if (!raw)
      return null
    const parsed = JSON.parse(raw) as { toolId?: unknown, recordType?: unknown }
    const toolId = parsed?.toolId != null ? String(parsed.toolId).trim() : ''
    const recordType = parsed?.recordType != null ? String(parsed.recordType).trim() : ''
    if (!toolId || !recordType)
      return null
    return { toolId, recordType }
  }
  catch {
    return null
  }
}

export function clearWorkflowRequestSeedPair(): void {
  try {
    sessionStorage.removeItem(SEED_KEY)
  }
  catch {
    // ignore
  }
}

/** 制度活化等场景：清空流式 last 与点击 seed */
export function clearWorkflowToolCaches(): void {
  clearWorkflowLastToolPair()
  clearWorkflowRequestSeedPair()
}

export function setWorkflowLastToolPair(toolId: string, recordType: string): void {
  const tid = toolId?.trim?.() ?? ''
  const rt = recordType?.trim?.() ?? ''
  if (!tid || !rt)
    return
  try {
    sessionStorage.setItem(STORAGE_KEY, JSON.stringify({ toolId: tid, recordType: rt }))
  }
  catch {
    // ignore
  }
}

export function getWorkflowLastToolPair(): { toolId: string, recordType: string } | null {
  try {
    const raw = sessionStorage.getItem(STORAGE_KEY)
    if (!raw)
      return null
    const parsed = JSON.parse(raw) as { toolId?: unknown, recordType?: unknown }
    const toolId = parsed?.toolId != null ? String(parsed.toolId).trim() : ''
    const recordType = parsed?.recordType != null ? String(parsed.recordType).trim() : ''
    if (!toolId || !recordType)
      return null
    return { toolId, recordType }
  }
  catch {
    return null
  }
}

/** get_tool_list 第 0 项的提问用 toolId / recordType（来自 userRole 首段） */
export function getToolListFirstPair(toolList: unknown[]): { toolId: string, recordType: string } {
  const row = Array.isArray(toolList) && toolList.length > 0 ? (toolList[0] as ToolListRow) : null
  return getToolQuestionPairFromRow(row)
}

/**
 * 组装「提问主工作流」等接口所需的 toolId / recordType：
 * 若已有流式返回缓存则优先；否则使用列表第 0 项的 userRole 首段（首次）。
 */
export function getWorkflowToolIdAndRecordTypeForRequest(toolList: unknown[]): { toolId: string, recordType: string } {
  const sessionToolId = typeof window !== 'undefined' ? sessionStorage.getItem('currentToolId') : null
  const fromList = resolveSubmitQuestionToolPair(sessionToolId, Array.isArray(toolList) ? (toolList as import('@/types/toolList').ToolListRow[]) : undefined)
  if (fromList.recordType)
    return fromList
  return getToolListFirstPair(toolList)
}

/** Chat 提交：与 resolveSubmitQuestionToolPair 一致（get_tool_list 当前项 userRole 第一段） */
export function getWorkflowToolIdAndRecordTypeForSubmit(sessionToolId?: string | null): { toolId: string, recordType: string } {
  const fromSession = typeof window !== 'undefined' ? sessionStorage.getItem('currentToolId') : null
  return resolveSubmitQuestionToolPair(sessionToolId ?? fromSession ?? undefined)
}
