import type {
  SystemConfig,
  ExternalIntegrations,
  RoutingPolicy,
  VehicleMaintenancePolicy,
  ChargePolicy,
  TaskAllocationPolicy,
  TrafficRule,
  DeviceManagementConfig,
  FleetLifecycleConfig,
  ScenarioTemplateConfig,
  LocationManagement,
  OpsConfig,
  AuthRoleConfig,
  CustomWidget,
  ConfigSection
} from '@/types/config'

export const DEFAULT_SYSTEM: SystemConfig = {
  dispatchLoopHz: 50,
  log: { level: 'info', rollDays: 7, maxSizeMB: 256 },
  security: { jwtExpireMin: 1440, enableSwagger: false, corsWhitelist: ['http://localhost:5173', 'https://*.intra'] }
}

export const DEFAULT_INTEGRATIONS: ExternalIntegrations = {
  mes: [{ id: 'mes-1', name: 'MES 主线', url: 'http://mes.lan/api', enabled: true }],
  wms: [{ id: 'wms-1', name: 'WMS 仓储', url: 'http://wms.lan/api', enabled: true }],
  rcs: []
}

export const DEFAULT_ROUTING: RoutingPolicy = {
  algorithm: 'astar',
  weights: { distance: 1, congestion: 0.5, turnPenalty: 0.2 },
  avoidance: [{ id: 'AV1', zoneId: 'Z-NORTH', rule: 'no-entry-while-loading' }],
  zoneSpeedLimits: [{ zoneId: 'Z-NARROW', maxSpeedMps: 0.5 }]
}

export const DEFAULT_VEHICLE: VehicleMaintenancePolicy = {
  lowBatteryThreshold: 0.3,
  criticalBatteryThreshold: 0.15,
  faultReport: { enabled: true, emailTo: ['ops@example.com'] },
  autoRepair: { enabled: false, cooldownSec: 600 }
}

export const DEFAULT_CHARGE: ChargePolicy = {
  allowMidTaskCharge: false,
  idleChargeAfterSec: 300,
  priority: [
    { id: 'CP1', condition: 'soc<0.2', weight: 100 },
    { id: 'CP2', condition: 'idle>5min', weight: 30 }
  ]
}

export const DEFAULT_TASK: TaskAllocationPolicy = {
  mode: 'leastLoad',
  loadBalance: true,
  maxQueuePerCar: 3
}

export const DEFAULT_TRAFFIC: TrafficRule = {
  intersections: [{ id: 'IX1', siteIds: ['S006', 'S007'], mode: 'mutex' }],
  mutex: [{ id: 'MZ1', zoneIds: ['Z-CROSS'] }],
  yields: [{ id: 'YD1', from: 'A 区', to: 'B 区', condition: 'priority<peer' }]
}

export const DEFAULT_AUTH: AuthRoleConfig = {
  roles: [
    {
      id: 'role-admin', name: '管理员', scope: 'Platform',
      permissions: ['*'],
      widgetGrants: []
    },
    {
      id: 'role-ops', name: '运营', scope: 'RCSMonitor',
      permissions: [
        'ops.car.pause', 'ops.car.resume', 'ops.car.gohome',
        'ops.task.pause', 'ops.task.cancel', 'ops.task.reassign',
        'ops.task.boostPriority', 'monitor.note.write'
      ],
      widgetGrants: [
        { widgetId: 'MapEditor', visibility: 'readonly' },
        { widgetId: 'CadToolbar', visibility: 'hidden' }
      ]
    }
  ],
  users: [
    { id: 'u-admin', username: 'admin', roles: ['role-admin'], enabled: true },
    { id: 'u-ops', username: 'ops', roles: ['role-ops'], enabled: true }
  ]
}

export const DEFAULT_DEVICE: DeviceManagementConfig = {
  drivers: [
    { id: 'drv-elev', deviceType: '电梯', driverName: 'OpcUaElevatorDriver', version: '1.2.0' },
    { id: 'drv-chrg', deviceType: '充电桩', driverName: 'ModbusChargerDriver', version: '1.0.5' },
    { id: 'drv-cam', deviceType: '摄像头', driverName: 'OnvifCameraDriver', version: '2.1.0' }
  ],
  devices: [
    { id: 'dev-elev-1', name: '#1 电梯', deviceType: '电梯', protocol: 'opc-ua', address: 'opc.tcp://10.0.2.20:4840', driverId: 'drv-elev', enabled: true },
    { id: 'dev-chrg-1', name: '充电桩-A1', deviceType: '充电桩', protocol: 'modbus-tcp', address: '10.0.2.30:502', driverId: 'drv-chrg', enabled: true }
  ],
  healthPolicy: { heartbeatSec: 5, offlineSec: 30 },
  alarmPolicy: {
    enabled: true,
    rules: [
      { level: 'warn', condition: 'offline>30s' },
      { level: 'error', condition: 'driverException' }
    ]
  }
}

export const DEFAULT_FLEET: FleetLifecycleConfig = {
  groups: [
    { id: 'G-A', name: 'A 区车队', floor: 'F1', region: 'A', carIds: ['C01', 'C02', 'C03'] },
    { id: 'G-B', name: 'B 区车队', floor: 'F1', region: 'B', carIds: ['C04', 'C05'] }
  ],
  ota: { enabled: true, batchSize: 2, rollbackOnFail: true },
  batchOps: { confirmationRequired: true, maxBatch: 10 },
  networkDiag: { rttThresholdMs: 80, packetLossThreshold: 0.02 }
}

export const DEFAULT_SCENARIO: ScenarioTemplateConfig = {
  templates: [
    { id: 'tpl-sps', name: 'SPS 物料配送', category: 'SPS', version: '1.0.0', baselineJson: '{}' },
    { id: 'tpl-pack', name: '电池 Pack 自动化产线', category: 'BatteryPack', version: '1.0.0', baselineJson: '{}' },
    { id: 'tpl-loop', name: '环线运行', category: 'Loop', version: '1.0.0', baselineJson: '{}' },
    { id: 'tpl-p2p', name: '点对点柔性搬运', category: 'P2P', version: '1.0.0', baselineJson: '{}' }
  ],
  dslPolicy: { enabled: true, schemaVersion: '1' },
  lowCode: { enabled: false, editor: 'json' },
  versionPolicy: { keepVersions: 10, allowRollback: true }
}

export const DEFAULT_LOCATION: LocationManagement = {
  locations: [
    { id: 'L01', code: 'A-01', name: 'A 区货架 1', siteId: 'S001', capacity: 20, occupied: 12 },
    { id: 'L02', code: 'A-02', name: 'A 区货架 2', siteId: 'S002', capacity: 20, occupied: 7 },
    { id: 'L03', code: 'B-01', name: 'B 区缓存', siteId: 'S003', capacity: 30, occupied: 25 }
  ],
  inventoryRules: [{ id: 'IR1', itemType: 'PalletA', minQty: 5, maxQty: 30 }]
}

export const DEFAULT_OPS: OpsConfig = {
  playback: { retentionDays: 30, samplingHz: 5 },
  logRetention: { hotDays: 7, coldDays: 180 },
  version: { keepReleases: 5 },
  monitor: {
    car: { propertyKeys: [], statusKeys: [], actionKeys: [] },
    site: { propertyKeys: [], statusKeys: [], actionKeys: [] },
    track: { propertyKeys: [], statusKeys: [], actionKeys: [] },
    carActionByType: {}
  }
}

export const DEFAULT_WIDGETS: { items: CustomWidget[] } = {
  items: [
    {
      id: 'widget-call-button', name: '呼叫按钮', schemaJson: '{"fields":[{"name":"siteId"}]}',
      layoutJson: '{"x":0,"y":0,"w":2,"h":1}', bindToScopes: ['RCSMonitor']
    }
  ]
}

export const CONFIG_DEFAULTS: Record<ConfigSection, unknown> = {
  system: DEFAULT_SYSTEM,
  integrations: DEFAULT_INTEGRATIONS,
  routing: DEFAULT_ROUTING,
  vehicle: DEFAULT_VEHICLE,
  charge: DEFAULT_CHARGE,
  task: DEFAULT_TASK,
  traffic: DEFAULT_TRAFFIC,
  auth: DEFAULT_AUTH,
  device: DEFAULT_DEVICE,
  fleet: DEFAULT_FLEET,
  scenario: DEFAULT_SCENARIO,
  location: DEFAULT_LOCATION,
  ops: DEFAULT_OPS,
  widget: DEFAULT_WIDGETS
}
