import { normalizeResponseData, requestJson } from "./request"

const OPEN_API_BASE = import.meta.env.VITE_OPEN_API_BASE || "/openApi"

export async function getEcologicalScopeStats(scopeKey) {
  const response = await requestJson(`${OPEN_API_BASE}/ecologicalProtection/rangeStats`, {
    method: "POST",
    timeout: 30000,
    params: { scopeKey },
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ scopeKey }),
  })
  const data = normalizeResponseData(response)
  return normalizeEcologicalScopeStats(Array.isArray(data) ? data[0] || {} : data || {})
}

const ECOLOGICAL_SCOPE_FIELD_MAP = {
  scope_key: "scopeKey",
  scope_name: "scopeName",
  scope_area_wan_mu: "scopeAreaWanMu",
  source_feature_count: "sourceFeatureCount",
  grassland_area_wan_mu: "grasslandAreaWanMu",
  wetland_area_wan_mu: "wetlandAreaWanMu",
  woodland_area_wan_mu: "woodlandAreaWanMu",
  grassland_fresh_yield_wan_ton: "grasslandFreshYieldWanTon",
  wetland_fresh_yield_wan_ton: "wetlandFreshYieldWanTon",
  grassland_mu_yield_jin: "grasslandMuYieldJin",
  wetland_mu_yield_jin: "wetlandMuYieldJin",
  grassland_vegetation_cover_percent: "grasslandVegetationCoverPercent",
  grassland_patch_count: "grasslandPatchCount",
  wetland_patch_count: "wetlandPatchCount",
  woodland_patch_count: "woodlandPatchCount",
  grassland_distribution: "grasslandDistribution",
  wetland_distribution: "wetlandDistribution",
  woodland_distribution: "woodlandDistribution",
  grassland_productivity: "grasslandProductivity",
  grassland_types: "grasslandTypes",
  zoning_structure: "zoningStructure",
  grassland_levels: "grasslandLevels",
  vegetation_cover_bands: "vegetationCoverBands",
  woodland_types: "woodlandTypes",
  woodland_quality: "woodlandQuality",
  area_method: "areaMethod",
  area_unit: "areaUnit",
  productivity_method: "productivityMethod",
}

function normalizeEcologicalScopeStats(raw = {}) {
  if (!raw || typeof raw !== "object") return {}
  return Object.entries(raw).reduce((result, [key, value]) => {
    result[key] = value
    const normalizedKey = ECOLOGICAL_SCOPE_FIELD_MAP[key]
    if (normalizedKey && result[normalizedKey] === undefined) {
      result[normalizedKey] = value
    }
    return result
  }, {})
}
