import type { ToolListRow } from '@/types/toolList'
import { getUserRolesForApi } from '@/lib/utils'

/** 与 ChatEditor 写入的 session 缓存键一致 */
export const TOOL_LIST_SESSION_KEY = 'toolList'

function asToolRows(toolList: unknown): ToolListRow[] {
  return Array.isArray(toolList) ? (toolList as ToolListRow[]) : []
}

/** 规范化 toolId：空串视为无工具（制度活化会话） */
export function normalizeToolId(toolId: unknown): string {
  if (toolId == null)
    return ''
  const s = String(toolId).trim()
  return s
}

/**
 * userRole：逗号分隔，依次为
 * 1 提问流 recordType；2 左侧常见问题 recordType；3 答后推荐问 recordType
 */
export function parseUserRoleRecordTypes(userRole: unknown): {
  questionRecordType: string
  commonQuestionRecordType: string
  recommendRecordType: string
} {
  const raw = userRole != null ? String(userRole) : ''
  const parts = raw.split(',').map(p => p.trim()).filter(p => p.length > 0)
  return {
    questionRecordType: parts[0] ?? '',
    commonQuestionRecordType: parts[1] ?? '',
    recommendRecordType: parts[2] ?? '',
  }
}

/** 列表中无 toolId（或空）的项视为「制度活化 / 通用」会话行 */
export function isGeneralInstitutionalToolRow(row: ToolListRow | null | undefined): boolean {
  if (!row)
    return false
  if (row.isGeneralSession === true || row.isGeneralSession === 1)
    return true
  return !normalizeToolId(row.toolId)
}

export function findGeneralToolRow(toolList: unknown): ToolListRow | null {
  const list = asToolRows(toolList)
  const hit = list.find(isGeneralInstitutionalToolRow)
  return hit ?? null
}

export function getFirstToolListRow(toolList: unknown): ToolListRow | null {
  const list = asToolRows(toolList)
  return list.length > 0 ? list[0] : null
}

export function findToolRowBySessionToolId(toolList: unknown, sessionToolId: string | null | undefined): ToolListRow | null {
  const list = asToolRows(toolList)
  const tid = normalizeToolId(sessionToolId)
  if (!tid)
    return getFirstToolListRow(toolList)
  return list.find(r => normalizeToolId(r.toolId) === tid) ?? null
}

/**
 * 提问接口用的 toolId + recordType（recordType 优先 userRole 首段，否则回退行上 recordType）
 */
export function getToolQuestionPairFromRow(row: ToolListRow | null | undefined): { toolId: string, recordType: string } {
  if (!row) {
    return { toolId: '', recordType: '' }
  }
  const toolId = normalizeToolId(row.toolId)
  const fromRole = parseUserRoleRecordTypes(row.userRole)
  const recordType = fromRole.questionRecordType
    || (row.recordType != null ? String(row.recordType).trim() : '')
  return { toolId, recordType }
}

/**
 * 提问接口统一解析 toolId / recordType：按当前会话工具从 get_tool_list 取行，
 * recordType 为 userRole 第一段（提问流），无则回退行上 recordType；无 toolId 时取制度活化/通用行。
 */
export function resolveSubmitQuestionToolPair(
  sessionToolId?: string | null,
  toolList?: ToolListRow[],
): { toolId: string, recordType: string } {
  const list = toolList ?? readToolListFromSessionStorage()
  const row = findToolRowBySessionToolId(list, sessionToolId)
  return getToolQuestionPairFromRow(row)
}

/** 左侧常见问题 recordType */
export function getCommonQuestionRecordTypeForToolRow(row: ToolListRow | null | undefined): string {
  if (!row)
    return ''
  const { commonQuestionRecordType, questionRecordType } = parseUserRoleRecordTypes(row.userRole)
  return commonQuestionRecordType || questionRecordType
    || (row.recordType != null ? String(row.recordType).trim() : '')
}

/** 答后推荐问 recordType */
export function getRecommendRecordTypeForToolRow(row: ToolListRow | null | undefined): string {
  if (!row)
    return ''
  const { recommendRecordType, questionRecordType } = parseUserRoleRecordTypes(row.userRole)
  return recommendRecordType || questionRecordType
    || (row.recordType != null ? String(row.recordType).trim() : '')
}

/** 是否走业务洞察常见问题（由列表行配置驱动，不写死名称或 toolId） */
export function toolRowUsesBusinessInsightCommonQuestions(row: ToolListRow | null | undefined): boolean {
  if (!row)
    return false
  if (row.commonQuestionApi === 'business_insight')
    return true
  return Array.isArray(row.businessInsightConfigTypes) && row.businessInsightConfigTypes.length > 0
}

export function getBusinessInsightConfigTypesForRow(row: ToolListRow | null | undefined): string[] {
  if (!row)
    return ['10']
  if (Array.isArray(row.businessInsightConfigTypes) && row.businessInsightConfigTypes.length > 0)
    return row.businessInsightConfigTypes.map(String)
  return ['10']
}

/** 新建会话进入聊天页后，是否需要与底部工具一致：拉历史并触发空问题首包（由配置驱动） */
export function toolRowTriggersEmptyQuestionBootstrap(row: ToolListRow | null | undefined): boolean {
  if (!row || !normalizeToolId(row.toolId))
    return false
  return Boolean(parseUserRoleRecordTypes(row.userRole).questionRecordType)
}

/** 从历史进入会话时，是否派发 shouldSendQuestion 空格触发静默补问（与 toolRowTriggersEmptyQuestionBootstrap 一致） */
export function toolRowTriggersHistoryEmptyQuestionSend(row: ToolListRow | null | undefined): boolean {
  return toolRowTriggersEmptyQuestionBootstrap(row)
}

export function readToolListFromSessionStorage(): ToolListRow[] {
  try {
    const raw = sessionStorage.getItem(TOOL_LIST_SESSION_KEY)
    if (!raw)
      return tryReadLegacyToolListCache()
    const parsed = JSON.parse(raw) as { toolList?: unknown, timestamp?: number }
    if (parsed?.toolList && Array.isArray(parsed.toolList))
      return asToolRows(parsed.toolList)
    if (Array.isArray(parsed))
      return asToolRows(parsed)
  }
  catch {
    // ignore
  }
  return tryReadLegacyToolListCache()
}

function tryReadLegacyToolListCache(): ToolListRow[] {
  try {
    const userRoles = getUserRolesForApi()
    const cacheKey = `toolList_${JSON.stringify(userRoles)}`
    const raw = sessionStorage.getItem(cacheKey)
    if (!raw)
      return []
    const { toolList } = JSON.parse(raw) as { toolList?: unknown }
    return asToolRows(toolList)
  }
  catch {
    return []
  }
}
