import { reflectionApi, emptyMonitorVisibilityMap, type MonitorVisibilityMap } from '@/api/reflection'
import { DEFAULT_OPS } from '@/mock/data/configs'
import type { MonitorOpsPolicy, OpsConfig } from '@/types/config'

export function defaultMonitorPolicy(): MonitorOpsPolicy {
  return JSON.parse(JSON.stringify(DEFAULT_OPS.monitor)) as MonitorOpsPolicy
}

export function normalizeOpsConfig(raw?: Partial<OpsConfig> | null): OpsConfig {
  const base = JSON.parse(JSON.stringify(DEFAULT_OPS)) as OpsConfig
  if (!raw) return base
  const monitor = {
    ...defaultMonitorPolicy(),
    ...(raw.monitor ?? {}),
    car: { ...defaultMonitorPolicy().car, ...(raw.monitor?.car ?? {}) },
    site: { ...defaultMonitorPolicy().site, ...(raw.monitor?.site ?? {}) },
    track: { ...defaultMonitorPolicy().track, ...(raw.monitor?.track ?? {}) },
    carActionByType: { ...(raw.monitor?.carActionByType ?? {}) }
  }
  return {
    ...base,
    ...raw,
    playback: { ...base.playback, ...(raw.playback ?? {}) },
    logRetention: { ...base.logRetention, ...(raw.logRetention ?? {}) },
    version: { ...base.version, ...(raw.version ?? {}) },
    monitor
  }
}

type MonitorConfigRoot = MonitorVisibilityMap & { carActionByType?: Record<string, string[]> }

function pickMonitorRoot(cfg: MonitorConfigRoot) {
  return {
    carActionByType: { ...(cfg.carActionByType ?? {}) },
    siteActionKeys: [...(cfg.site?.methods ?? [])],
    trackActionKeys: [...(cfg.track?.methods ?? [])]
  }
}

/**
 * 从 SimpleLite simple.json 加载地图监控配置（运行时唯一可信源）。
 * Platform ops 里的 monitor 仅作备份；以 SimpleLite 为准覆盖表单。
 */
export async function loadMonitorSettingsIntoOps(payload: OpsConfig): Promise<OpsConfig> {
  const next = normalizeOpsConfig(payload)
  try {
    const mc = await reflectionApi.getMonitorConfig()
    const picked = pickMonitorRoot(mc.config as MonitorConfigRoot)
    next.monitor.carActionByType = picked.carActionByType
    next.monitor.site.actionKeys = picked.siteActionKeys
    next.monitor.track.actionKeys = picked.trackActionKeys
  } catch {
    // SimpleLite 未连接：退回 Platform payload 中已有的 monitor（若有）
  }
  return next
}

/**
 * 将运营维护表单中的地图监控配置写入 SimpleLite（simple.json）。
 * 保留「地图监控配置」页面对 fields/status 的既有设置，只更新动作相关字段。
 */
export async function saveMonitorSettingsFromOps(payload: OpsConfig): Promise<void> {
  const monitor = normalizeOpsConfig(payload).monitor
  let current: MonitorConfigRoot = emptyMonitorVisibilityMap()
  try {
    const mc = await reflectionApi.getMonitorConfig()
    current = mc.config as MonitorConfigRoot
  } catch {
    // 无现有配置时用空壳，仍可写入动作白名单
  }

  await reflectionApi.saveMonitorConfig({
    car: {
      fields: [...(current.car?.fields ?? [])],
      status: [...(current.car?.status ?? [])],
      methods: [...(current.car?.methods ?? [])]
    },
    site: {
      fields: [...(current.site?.fields ?? [])],
      status: [...(current.site?.status ?? [])],
      methods: [...monitor.site.actionKeys]
    },
    track: {
      fields: [...(current.track?.fields ?? [])],
      status: [...(current.track?.status ?? [])],
      methods: [...monitor.track.actionKeys]
    },
    carActionByType: { ...monitor.carActionByType }
  })
}

/** @deprecated 使用 loadMonitorSettingsIntoOps */
export const mergeMonitorFromSimpleLite = loadMonitorSettingsIntoOps

/** @deprecated 使用 saveMonitorSettingsFromOps */
export const syncOpsMonitorToSimpleLite = saveMonitorSettingsFromOps
