import { getSmartChartsForQuestion } from "./smartChartApi"
import {
  getYakForecastRows as fetchYakForecastRows,
  getYakStructureRows as fetchYakStructureRows,
  getYakTownRows as fetchYakTownRows,
  getYakTradeRows as fetchYakTradeRows,
} from "./yakApi"
import {
  businessMatrixRows,
  centerOrbitNodes,
  dataFlowRows,
  homeHeroStats,
  homeTopStats,
  resourceCompositionRows,
  supportRows,
  townSynergyRows,
  tradeRows,
  yakTownRows as homeYakTownRows,
} from "@/views/home/data"
import {
  pastureAgeRows,
  pastureCoreRows,
  pastureGenderRows,
  pastureGrasslandRows,
  pastureListRows,
  pastureMapRows,
  pastureOnlineRows,
  pastureSeasonRows,
  pastureStructureRows,
  pastureTopStats,
  pastureTownRows,
} from "@/views/pastureManagement/data"
import {
  BALANCE_CALCULATION_PARAMS,
  balanceFallbackRows,
  balanceTownRows,
  countyBalanceRow,
} from "@/views/grassLivestockBalance/data"
import {
  engineeringAnalysisPanels,
  engineeringAnalysisProjectFeatures,
  engineeringAnalysisTopStats,
  parkCoreRows,
  parkPanels,
  parkTopStats,
  parkTownRows,
  restorationPanels,
  restorationTopStats,
} from "@/views/ecologicalProtection/data"
import {
  breedingLevelRows,
  forageSecurityRows,
  industryChainListRows,
  industryFinancialRows,
  industryOverviewRows,
  industryPointRows,
  industryStageRows,
  industryTopStats,
  industryValueRows,
  processingPointRows,
  processingAbilityRows,
  serviceCapabilityRows,
  stageCompositionRows,
  supportPointRows,
} from "@/views/yakIndustryChain/data"

const PAGE_NAME = "智慧管理"
const DATASET_ROW_LIMIT = 80

const INTENT_DEFS = [
  {
    key: "livestock_balance",
    label: "草畜平衡",
    patterns: [/草畜|平衡|承载|载畜|超载|放牧压力|轮牧|休牧/],
    build: buildBalanceDatasets,
  },
  {
    key: "yak",
    label: "牦牛管理",
    patterns: [/牦牛|耗牛|犛牛|存栏|畜群|牛群|牛犊|母牛|公牛|出栏|交易|预测/],
    build: buildYakDatasets,
  },
  {
    key: "pasture",
    label: "牧户管理",
    patterns: [/牧户|牧场|联户|在线|年龄|性别|户均|草场/],
    build: buildPastureDatasets,
  },
  {
    key: "ecology",
    label: "生态保护",
    patterns: [/生态|公益林|湿地|草地|林地|保护|修复|红线|公园|自然保护地|工程/],
    build: buildEcologyDatasets,
  },
  {
    key: "industry",
    label: "牦牛产业链",
    patterns: [/产业链|产业|主体|加工|屠宰|饲草|储草|家庭生态牧场|品牌|服务能力/],
    build: buildIndustryDatasets,
  },
]

export async function buildSmartQuestionContext(question, options = {}) {
  const normalizedQuestion = normalizeQuestionText(question)
  const pagePath = options.pagePath || window.location.hash || window.location.pathname
  const warnings = []
  const chartsPromise = getSmartChartsForQuestion(normalizedQuestion, pagePath, PAGE_NAME)
    .catch((error) => {
      warnings.push(getFriendlyContextError(error, "辅助图表暂不可用"))
      return []
    })

  const selectedIntents = selectIntents(normalizedQuestion)
  const datasetResults = await Promise.all(selectedIntents.map((intent) => intent.build(normalizedQuestion, warnings)))
  const datasets = uniqueDatasets(datasetResults.flat())
  const charts = await chartsPromise
  const isOverviewIntent = selectedIntents.length === 1 && selectedIntents[0]?.key === "overview"
  const mergedDatasets = datasets.length ? datasets : (isOverviewIntent ? buildOverviewDatasets() : [])
  const scope = inferScope(normalizedQuestion, mergedDatasets)
  const context = {
    question: normalizedQuestion,
    pageName: PAGE_NAME,
    pagePath,
    scope,
    intents: selectedIntents.map((intent) => ({ key: intent.key, label: intent.label })),
    datasets: mergedDatasets,
    charts,
    notes: buildContextNotes(mergedDatasets, charts, warnings),
    warnings,
  }

  return {
    ...context,
    insights: buildContextInsights(context),
  }
}

export function buildSmartContextAnswer(context = {}) {
  const datasets = Array.isArray(context.datasets) ? context.datasets : []
  const insights = Array.isArray(context.insights) ? context.insights : []
  const scope = context.scope || "红原县"
  const sourceTitles = datasets.slice(0, 4).map((item) => item.title).filter(Boolean)
  const insightLines = insights.slice(0, 5).map((item) => `- ${item.label}：${item.value}${item.note ? `（${item.note}）` : ""}`)
  const notes = (context.notes || []).slice(0, 3).map((item) => `- ${item}`)

  return [
    "**总体情况**",
    `已按${scope}相关业务数据整理本次问题的业务信息。`,
    "",
    "**已整理数据**",
    ...(sourceTitles.length ? sourceTitles.map((title) => `- ${title}`) : ["- 平台综合业务数据"]),
    "",
    insightLines.length ? "**关键数据**" : "",
    ...insightLines,
    "",
    notes.length ? "**数据说明**" : "",
    ...notes,
  ].filter(Boolean).join("\n")
}

function selectIntents(question) {
  const matched = INTENT_DEFS.filter((intent) => intent.patterns.some((pattern) => pattern.test(question)))
  if (matched.length) return matched
  return [{
    key: "overview",
    label: "综合总览",
    build: () => buildOverviewDatasets(),
  }]
}

function buildOverviewDatasets() {
  return [
    dataset("home.topStats", "首页核心指标", homeTopStats, "平台业务汇总数据"),
    dataset("home.heroStats", "资源与草畜概览", homeHeroStats, "平台业务汇总数据"),
    dataset("home.resourceComposition", "资源构成", resourceCompositionRows, "平台业务汇总数据"),
    dataset("home.businessMatrix", "业务矩阵", businessMatrixRows, "平台业务汇总数据"),
    dataset("home.townSynergy", "乡镇林草湿与牦牛协同", townSynergyRows, "平台业务汇总数据"),
    dataset("home.yakTown", "首页牦牛乡镇排行", homeYakTownRows, "平台业务汇总数据"),
    dataset("home.trade", "首页交易结构", tradeRows, "平台业务汇总数据"),
    dataset("home.support", "首页支撑产业", supportRows, "平台业务汇总数据"),
    dataset("home.dataFlow", "数据流汇总", dataFlowRows, "平台业务汇总数据"),
    dataset("home.centerOrbit", "首页中心节点", centerOrbitNodes, "平台业务汇总数据"),
  ]
}

async function buildYakDatasets(question, warnings = []) {
  const [townResult, structureResult, forecastResult, tradeResult] = await Promise.allSettled([
    fetchYakTownRows(),
    fetchYakStructureRows(),
    fetchYakForecastRows(),
    fetchYakTradeRows(),
  ])
  appendDatasetWarning(townResult, warnings, "牦牛乡镇存栏数据暂未取得")
  appendDatasetWarning(structureResult, warnings, "牦牛畜群结构数据暂未取得")
  appendDatasetWarning(forecastResult, warnings, "牦牛预测数据暂未取得")
  appendDatasetWarning(tradeResult, warnings, "牦牛交易数据暂未取得")

  const townRows = normalizeActualYakTownRows(getSettledRows(townResult))
  const structureRows = normalizeActualYakMetricRows(getSettledRows(structureResult))
  const forecastRows = normalizeActualYakForecastRows(getSettledRows(forecastResult))
  const tradeRows = normalizeActualYakMetricRows(getSettledRows(tradeResult))

  return [
    dataset("yak.town", "乡镇牦牛存栏分布", townRows, "牦牛管理接口数据"),
    dataset("yak.structureRows", "畜群结构数量", structureRows, "牦牛管理接口数据"),
    dataset("yak.forecastRows", "牦牛月度预测", forecastRows, "牦牛管理接口数据"),
    dataset("yak.tradeImpact", "交易影响", tradeRows, "牦牛交易接口数据"),
  ]
}

function getSettledRows(result) {
  return result.status === "fulfilled" && Array.isArray(result.value) ? result.value : []
}

function appendDatasetWarning(result, warnings, fallback) {
  if (result.status === "rejected") {
    warnings.push(getFriendlyContextError(result.reason, fallback))
  }
}

function normalizeActualYakTownRows(rows = []) {
  return rows
    .map((row, index) => {
      const name = String(row.name || row.areaName || row.area_name || row.townName || row.zoneName || "").trim()
      const count = toDatasetNumber(row.count ?? row.value ?? row.number ?? row.yakCount ?? row.yak_count)
      return {
        key: row.key || row.id || row.areaCode || row.area_code || `${name || "yak-town"}-${index}`,
        name,
        count,
        value: count,
        unit: row.unit || "头",
      }
    })
    .filter((row) => row.name && Number.isFinite(row.count))
    .sort((a, b) => b.count - a.count)
}

function normalizeActualYakMetricRows(rows = []) {
  return rows
    .map((row, index) => {
      const name = String(row.name || row.label || row.type || row.key || "").trim()
      const count = toDatasetNumber(row.count ?? row.value ?? row.number ?? row.yakCount ?? row.headCount ?? row.amount)
      return {
        key: row.key || row.id || `${name || "yak-metric"}-${index}`,
        name,
        count,
        value: count,
        unit: row.unit || "头",
        extra: row.extra || "",
      }
    })
    .filter((row) => row.name && Number.isFinite(row.count))
    .sort((a, b) => b.count - a.count)
}

function normalizeActualYakForecastRows(rows = []) {
  return rows
    .map((row, index) => {
      const name = String(row.name || row.label || row.month || row.date || row.time || "").trim()
      const stock = toDatasetNumber(row.stock ?? row.count ?? row.value ?? row.number ?? row.yakCount)
      return {
        key: row.key || row.id || `${name || "yak-forecast"}-${index}`,
        name,
        label: name,
        stock,
        count: stock,
        value: stock,
        unit: row.unit || "头",
        extra: row.extra || "",
      }
    })
    .filter((row) => row.name && Number.isFinite(row.stock))
}

function buildBalanceDatasets(question) {
  const focusRow = findBalanceContextRow(question)
  const focusName = focusRow?.name || "红原县"
  return [
    dataset("balance.target", `${focusName}草畜平衡`, [focusRow], "平台业务汇总数据"),
    dataset("balance.county", "全县草畜平衡", [countyBalanceRow], "平台业务汇总数据"),
    dataset("balance.town", "乡镇草畜平衡", balanceTownRows, "平台业务汇总数据"),
    dataset("balance.fallbackRows", "草畜平衡兜底数据", balanceFallbackRows, "平台业务汇总数据"),
    dataset("balance.params", "草畜平衡计算参数", [BALANCE_CALCULATION_PARAMS], "平台业务汇总数据"),
  ]
}

function buildPastureDatasets() {
  return [
    dataset("pasture.core", "牧户核心指标", pastureCoreRows, "平台业务汇总数据"),
    dataset("pasture.topStats", "牧户顶部指标", pastureTopStats, "平台业务汇总数据"),
    dataset("pasture.town", "牧户乡镇分布", pastureTownRows, "平台业务汇总数据"),
    dataset("pasture.online", "牧户在线率", pastureOnlineRows, "平台业务汇总数据"),
    dataset("pasture.structure", "牧户年龄性别结构", pastureStructureRows, "平台业务汇总数据"),
    dataset("pasture.age", "牧户年龄结构", pastureAgeRows, "平台业务汇总数据"),
    dataset("pasture.gender", "牧户性别结构", pastureGenderRows, "平台业务汇总数据"),
    dataset("pasture.list", "牧户示例列表", pastureListRows, "平台业务汇总数据"),
    dataset("pasture.grassland", "牧户草场资源", pastureGrasslandRows, "平台业务汇总数据"),
    dataset("pasture.season", "牧户季节草场", pastureSeasonRows, "平台业务汇总数据"),
    dataset("pasture.map", "牧户地图统计", pastureMapRows, "平台业务汇总数据"),
  ]
}

function buildEcologyDatasets() {
  return [
    dataset("ecology.parkTopStats", "生态保护核心指标", parkTopStats, "平台业务汇总数据"),
    dataset("ecology.parkCore", "国家公园核心指标", parkCoreRows, "平台业务汇总数据"),
    dataset("ecology.parkTownRows", "国家公园乡镇数据", parkTownRows, "平台业务汇总数据"),
    dataset("ecology.restorationTopStats", "生态修复项目汇总", restorationTopStats, "平台业务汇总数据"),
    dataset("ecology.engineeringTopStats", "生态工程分析指标", engineeringAnalysisTopStats, "平台业务汇总数据"),
    dataset("ecology.engineeringProjectFeatures", "工程分析项目点", engineeringAnalysisProjectFeatures, "平台业务汇总数据"),
    dataset("ecology.parkPanels", "生态保护图表数据", flattenPanelRows(parkPanels), "平台业务汇总数据"),
    dataset("ecology.restorationPanels", "生态修复图表数据", flattenPanelRows(restorationPanels), "平台业务汇总数据"),
    dataset("ecology.engineeringAnalysisPanels", "工程分析图表数据", flattenPanelRows(engineeringAnalysisPanels), "平台业务汇总数据"),
    dataset("home.resourceComposition", "林草湿资源构成", resourceCompositionRows, "平台业务汇总数据"),
    dataset("home.townSynergy", "乡镇林草湿与牦牛协同", townSynergyRows, "平台业务汇总数据"),
  ]
}

function buildIndustryDatasets() {
  return [
    dataset("industry.topStats", "产业链核心指标", industryTopStats, "平台业务汇总数据"),
    dataset("industry.overview", "产业链总览", industryOverviewRows, "平台业务汇总数据"),
    dataset("industry.stageComposition", "产业阶段构成", stageCompositionRows, "平台业务汇总数据"),
    dataset("industry.stageRows", "产业阶段说明", industryStageRows, "平台业务汇总数据"),
    dataset("industry.breedingLevel", "养殖水平", breedingLevelRows, "平台业务汇总数据"),
    dataset("industry.forageSecurity", "饲草保障能力", forageSecurityRows, "平台业务汇总数据"),
    dataset("industry.value", "产业价值指标", industryValueRows, "平台业务汇总数据"),
    dataset("industry.processingAbility", "加工能力指标", processingAbilityRows, "平台业务汇总数据"),
    dataset("industry.serviceCapability", "服务能力指标", serviceCapabilityRows, "平台业务汇总数据"),
    dataset("industry.financial", "金融服务", industryFinancialRows, "平台业务汇总数据"),
    dataset("industry.supportPoints", "饲草储备点位", supportPointRows, "平台业务汇总数据"),
    dataset("industry.processingPoints", "加工屠宰点位", processingPointRows, "平台业务汇总数据"),
    dataset("industry.points", "产业链点位", industryPointRows, "平台业务汇总数据"),
    dataset("industry.list", "产业链主体列表", industryChainListRows, "平台业务汇总数据"),
  ]
}

function findBalanceContextRow(question) {
  return balanceTownRows.find((row) => containsName(question, row.name)) || countyBalanceRow
}

function dataset(id, title, rows, sourceLabel) {
  return {
    id,
    title,
    suggestedView: inferSuggestedView(title, rows),
    source: { label: sourceLabel || "平台展示数据" },
    rows: sanitizeRows(rows),
  }
}

function sanitizeRows(rows) {
  return (Array.isArray(rows) ? rows : [])
    .slice(0, DATASET_ROW_LIMIT)
    .map((row) => sanitizeValue(row))
    .filter((row) => row && typeof row === "object")
}

function sanitizeValue(value, depth = 0) {
  if (depth > 4 || value === undefined || typeof value === "function") return null
  if (value === null || ["string", "number", "boolean"].includes(typeof value)) return value
  if (Array.isArray(value)) return value.slice(0, 30).map((item) => sanitizeValue(item, depth + 1))
  if (typeof value === "object") {
    return Object.entries(value).reduce((result, [key, item]) => {
      if (["icon", "color", "tone", "image", "cover", "component"].includes(key)) return result
      result[key] = sanitizeValue(item, depth + 1)
      return result
    }, {})
  }
  return String(value)
}

function uniqueDatasets(datasets = []) {
  const seen = new Set()
  return datasets.filter((item) => {
    if (!item?.rows?.length || seen.has(item.id)) return false
    seen.add(item.id)
    return true
  })
}

function buildContextNotes(datasets, charts, warnings) {
  return [
    ...warnings,
  ].filter(Boolean)
}

function buildContextInsights(context) {
  const insights = []
  ;(context.datasets || []).some((item) => {
    const metric = firstMetricFromDataset(item)
    if (metric) insights.push(metric)
    return insights.length >= 5
  })
  ;(context.charts || []).some((chart) => {
    const rows = (chart.rows || []).filter((row) => Number.isFinite(Number(row.value)))
    if (!rows.length) return false
    const sortedRows = rows.slice().sort((a, b) => Number(b.value || 0) - Number(a.value || 0))
    const percentLike = chart.unit === "%" || /率|占比|比例/.test(chart.title || "")
    const chartValue = percentLike ? sortedRows[0]?.value : rows.reduce((sum, row) => sum + Number(row.value || 0), 0)
    const chartName = percentLike && sortedRows[0]?.name ? `${chart.title || "关联图表"}：${sortedRows[0].name}` : chart.title || "关联图表"
    insights.push({
      label: chartName,
      value: `${formatNumber(chartValue)}${chart.unit || ""}`,
      note: rows.length > 1 ? (percentLike ? "数值较高项" : `覆盖 ${rows.length} 项`) : "",
    })
    return insights.length >= 5
  })
  return insights.slice(0, 5)
}

function firstMetricFromDataset(datasetItem) {
  const row = (datasetItem.rows || []).find(Boolean)
  if (!row) return null
  const name = row.name || row.areaName || row.zh || row.label || datasetItem.title
  const hasBalanceRate = row.overloadRate !== undefined || row.overloadrate !== undefined
  const value = hasBalanceRate
    ? row.overloadRate ?? row.overloadrate
    : row.value ?? row.yakNumber ?? row.livestockCapacity ?? row.areaRange
  if (value === undefined || value === null || value === "") return null
  const unit = row.unit || (hasBalanceRate ? "%" : row.yakNumber !== undefined || row.livestockCapacity !== undefined ? "头" : "")
  return {
    label: hasBalanceRate ? `${name}超载率` : name,
    value: `${formatNumber(value)}${unit}`,
    note: hasBalanceRate ? row.level || datasetItem.title : datasetItem.title,
  }
}

function flattenPanelRows(panels = {}) {
  return Object.entries(panels || {}).flatMap(([groupKey, rows]) => (
    (Array.isArray(rows) ? rows : []).flatMap((panel) => {
      const panelRows = Array.isArray(panel?.rows)
        ? panel.rows
        : Array.isArray(panel?.data)
          ? panel.data
          : []
      return panelRows.map((row) => ({
        groupKey,
        panelKey: panel.key,
        panelTitle: panel.title,
        ...row,
      }))
    })
  ))
}

function inferScope(question, datasets) {
  const town = balanceTownRows.find((row) => containsName(question, row.name))
  if (town) return town.name
  const balanceTarget = datasets.find((item) => item.id === "balance.target")?.rows?.[0]
  if (balanceTarget?.name) return balanceTarget.name
  if (balanceTarget?.areaName) return balanceTarget.areaName
  return "红原县"
}

function inferSuggestedView(title, rows) {
  if (!Array.isArray(rows) || rows.length <= 1) return "metrics"
  if (/结构|构成|占比|比例/.test(title)) return "pie"
  if (/趋势|预测/.test(title)) return "line"
  return "bar-table"
}

function containsName(question, name) {
  const text = normalizeQuestionText(question)
  const shortName = String(name || "").replace(/(县|镇|村|乡|牧场|牧户|联户)$/g, "")
  return Boolean(name && (text.includes(name) || (shortName && text.includes(shortName))))
}

function normalizeQuestionText(value) {
  return String(value || "")
    .replace(/耗牛/g, "牦牛")
    .replace(/犛牛/g, "牦牛")
    .trim()
}

function getFriendlyContextError(error, fallback) {
  const message = String(error?.message || "")
  if (error?.code === 401 || error?.code === "401" || /未登录|授权|Unauthorized|HTTP 401/i.test(message)) {
    return "当前登录状态已失效，部分接口数据未取得"
  }
  if (/timeout|timed out|超时/i.test(message)) return `${fallback}，接口响应超时`
  return fallback
}

function toDatasetNumber(value) {
  if (value === undefined || value === null || value === "") return NaN
  const number = Number(String(value).replace(/,/g, "").replace(/%/g, ""))
  return Number.isFinite(number) ? number : NaN
}

function formatNumber(value) {
  const number = Number(String(value).replace(/,/g, ""))
  if (!Number.isFinite(number)) return value || "--"
  return number.toLocaleString("zh-CN", { maximumFractionDigits: 2 })
}
