/**
 * 配置中心 13+1 维度强类型（与 Platform.Server/Configs 一一对齐，字段命名追随 ARCHITECTURE.md §9）。
 */

export interface LogPolicy {
  level: 'trace' | 'debug' | 'info' | 'warn' | 'error'
  rollDays: number
  maxSizeMB: number
}

export interface SecurityPolicy {
  jwtExpireMin: number
  enableSwagger: boolean
  corsWhitelist: string[]
}

export interface SystemConfig {
  dispatchLoopHz: number
  log: LogPolicy
  security: SecurityPolicy
}

export interface MesEndpoint { id: string; name: string; url: string; enabled: boolean }
export interface WmsEndpoint { id: string; name: string; url: string; enabled: boolean }
export interface RcsEndpoint { id: string; name: string; url: string; enabled: boolean }

export interface ExternalIntegrations {
  mes: MesEndpoint[]
  wms: WmsEndpoint[]
  rcs: RcsEndpoint[]
}

export interface AvoidanceRule { id: string; zoneId: string; rule: string }
export interface ZoneSpeedLimit { zoneId: string; maxSpeedMps: number }

export interface RoutingPolicy {
  algorithm: 'dijkstra' | 'astar' | 'custom'
  weights: Record<string, number>
  avoidance: AvoidanceRule[]
  zoneSpeedLimits: ZoneSpeedLimit[]
}

export interface FaultReportPolicy { enabled: boolean; emailTo: string[] }
export interface AutoRepairPolicy { enabled: boolean; cooldownSec: number }

export interface VehicleMaintenancePolicy {
  lowBatteryThreshold: number
  criticalBatteryThreshold: number
  faultReport: FaultReportPolicy
  autoRepair: AutoRepairPolicy
}

export interface ChargePriorityRule { id: string; condition: string; weight: number }

export interface ChargePolicy {
  allowMidTaskCharge: boolean
  idleChargeAfterSec: number
  priority: ChargePriorityRule[]
}

export type AllocationMode = 'roundRobin' | 'nearest' | 'leastLoad' | 'custom'

export interface TaskAllocationPolicy {
  mode: AllocationMode
  loadBalance: boolean
  maxQueuePerCar: number
}

export interface IntersectionPolicy { id: string; siteIds: string[]; mode: 'mutex' | 'rotation' }
export interface ZoneMutex { id: string; zoneIds: string[] }
export interface DynamicYield { id: string; from: string; to: string; condition: string }

export interface TrafficRule {
  intersections: IntersectionPolicy[]
  mutex: ZoneMutex[]
  yields: DynamicYield[]
}

export type DeviceProtocol = 'modbus-tcp' | 'opc-ua' | 'http-rest' | 'mqtt' | 'onvif' | 'tcp-priv'

export interface DeviceDriverBinding { id: string; deviceType: string; driverName: string; version: string }
export interface DeviceInstance {
  id: string
  name: string
  deviceType: string
  protocol: DeviceProtocol
  address: string
  driverId: string
  enabled: boolean
}
export interface DeviceHealthPolicy { heartbeatSec: number; offlineSec: number }
export interface AlarmPolicy { enabled: boolean; rules: Array<{ level: string; condition: string }> }

export interface DeviceManagementConfig {
  drivers: DeviceDriverBinding[]
  devices: DeviceInstance[]
  healthPolicy: DeviceHealthPolicy
  alarmPolicy: AlarmPolicy
}

export interface FleetGroup { id: string; name: string; floor: string; region: string; carIds: string[] }
export interface OtaPolicy { enabled: boolean; batchSize: number; rollbackOnFail: boolean }
export interface BatchOpsPolicy { confirmationRequired: boolean; maxBatch: number }
export interface NetworkDiagPolicy { rttThresholdMs: number; packetLossThreshold: number }

export interface FleetLifecycleConfig {
  groups: FleetGroup[]
  ota: OtaPolicy
  batchOps: BatchOpsPolicy
  networkDiag: NetworkDiagPolicy
}

export interface ScenarioTemplate {
  id: string
  name: string
  category: 'SPS' | 'BatteryPack' | 'Loop' | 'P2P' | 'Custom'
  version: string
  baselineJson: string
}
export interface TemplateDslPolicy { enabled: boolean; schemaVersion: string }
export interface LowCodePolicy { enabled: boolean; editor: 'visual' | 'json' }
export interface TemplateVersionPolicy { keepVersions: number; allowRollback: boolean }

export interface ScenarioTemplateConfig {
  templates: ScenarioTemplate[]
  dslPolicy: TemplateDslPolicy
  lowCode: LowCodePolicy
  versionPolicy: TemplateVersionPolicy
}

export interface Location {
  id: string
  code: string
  name: string
  siteId: string
  capacity: number
  occupied: number
}
export interface InventoryRule { id: string; itemType: string; minQty: number; maxQty: number }

export interface LocationManagement {
  locations: Location[]
  inventoryRules: InventoryRule[]
}

export interface PlaybackPolicy { retentionDays: number; samplingHz: number }
export interface LogRetention { hotDays: number; coldDays: number }
export interface VersionPolicy { keepReleases: number }
export interface MonitorPanelPolicy {
  propertyKeys: string[]
  statusKeys: string[]
  actionKeys: string[]
}
export interface MonitorOpsPolicy {
  car: MonitorPanelPolicy
  site: MonitorPanelPolicy
  track: MonitorPanelPolicy
  carActionByType: Record<string, string[]>
}

export interface OpsConfig {
  playback: PlaybackPolicy
  logRetention: LogRetention
  version: VersionPolicy
  monitor: MonitorOpsPolicy
}

export interface CustomWidget {
  id: string
  name: string
  schemaJson: string
  layoutJson: string
  bindToScopes: Array<'Platform' | 'RCSMonitor'>
}

export interface AuthRole {
  id: string
  name: string
  scope: 'Platform' | 'RCSMonitor' | '*'
  permissions: string[]
  widgetGrants: Array<{ widgetId: string; visibility: 'hidden' | 'readonly' | 'interactive' }>
}

export interface AuthRoleConfig {
  roles: AuthRole[]
  users: Array<{ id: string; username: string; roles: string[]; enabled: boolean }>
}

export type ConfigSection =
  | 'system'
  | 'integrations'
  | 'routing'
  | 'vehicle'
  | 'charge'
  | 'task'
  | 'traffic'
  | 'auth'
  | 'device'
  | 'fleet'
  | 'scenario'
  | 'location'
  | 'ops'
  | 'widget'

export interface ConfigEnvelope<T = unknown> {
  section: ConfigSection
  version: number
  updatedAt: string
  payload: T
}

export const CONFIG_SECTIONS: Array<{ key: ConfigSection; label: string; icon?: string }> = [
  { key: 'system', label: '系统级配置' },
  { key: 'integrations', label: '外部系统对接' },
  { key: 'routing', label: '路径规划策略' },
  { key: 'vehicle', label: '车辆维护策略' },
  { key: 'charge', label: '充电逻辑' },
  { key: 'task', label: '任务分配机制' },
  { key: 'traffic', label: '交通管制规则' },
  { key: 'auth', label: '权限与角色管理' },
  { key: 'device', label: '第三方设备统一接入' },
  { key: 'fleet', label: '机器人群组与车队全生命周期' },
  { key: 'scenario', label: '业务场景模板化' },
  { key: 'location', label: '库位管理' },
  { key: 'ops', label: '运营维护' },
  { key: 'widget', label: '自定义控件管理' }
]
