import http from './http'
import { reflectionApi, type ReflectionObject } from './reflection'
import type { Site, Track } from '@/types/map'
import type { Car, CarState } from '@/types/car'
import type { Mission, MissionStatus } from '@/types/mission'
import { mockSites, mockTracks, mockCars, mockMissions } from '@/mock/server'

/** 设为 true 时使用本地 Mock；默认走 YARP → SimpleLite :8222。
 *  与 auth.ts / config.ts / ops.ts 统一走 VITE_USE_MOCK 开关（替代旧的 VITE_PROJECTION_MOCK）。 */
const MOCK = import.meta.env.VITE_USE_MOCK === 'true'

export async function listSites(): Promise<Site[]> {
  if (MOCK) return mockSites()
  const { data } = await http.get<Site[]>('/sl/projection/sites')
  return data
}

export async function listTracks(): Promise<Track[]> {
  if (MOCK) return mockTracks()
  const { data } = await http.get<Track[]>('/sl/projection/tracks')
  return data
}

function mapStatusToCarState(status?: string | null): CarState {
  if (!status) return 'idle'
  const s = status.toLowerCase()
  if (/fault|error|failed|故障|异常|失联|超时|检修/.test(s)) return 'fault'
  if (/charg|充电/.test(s)) return 'charging'
  if (/pause|暂停|挂起/.test(s)) return 'paused'
  if (/offline|离线/.test(s)) return 'offline'
  if (/run|busy|working|运行|工作|执行|忙/.test(s)) return 'running'
  return 'idle'
}

function mapStatusToMissionStatus(status?: string | null): MissionStatus {
  if (!status) return 'queued'
  const s = status.toLowerCase()
  if (/run|运行|执行/.test(s)) return 'running'
  if (/pause|暂停|挂起/.test(s)) return 'paused'
  if (/complete|done|完成|成功/.test(s)) return 'completed'
  if (/cancel|取消|中止/.test(s)) return 'cancelled'
  if (/fail|error|fault|失败|异常/.test(s)) return 'failed'
  if (/assign|分配/.test(s)) return 'assigned'
  return 'queued'
}

function carFromReflection(row: ReflectionObject): Car {
  return {
    id: `C${String(row.id).padStart(2, '0')}`,
    rawId: row.id,
    name: row.name,
    typeName: row.typeName,
    x: 0,
    y: 0,
    theta: 0,
    batterySoc: 0.8,
    state: mapStatusToCarState(row.status),
    lastUpdate: new Date().toISOString(),
    group: row.layer ?? undefined
  }
}

function missionFromReflection(row: ReflectionObject): Mission {
  return {
    id: `M${String(row.id).padStart(2, '0')}`,
    name: row.name,
    typeName: row.typeName,
    priority: 50,
    status: mapStatusToMissionStatus(row.status),
    steps: [],
    createdAt: new Date().toISOString()
  }
}

async function listCarsFromReflection(): Promise<Car[]> {
  const rows = await reflectionApi.listObjects('car')
  return rows.map(carFromReflection)
}

async function listMissionsFromReflection(): Promise<Mission[]> {
  const rows = await reflectionApi.listObjects('mission')
  return rows.map(missionFromReflection)
}

/** 优先走 SimpleLite /projection/cars；502 或空列表时回退 reflection 对象列表（与 3D 场景同源）。 */
export async function listCars(): Promise<Car[]> {
  if (MOCK) return mockCars()
  try {
    const { data } = await http.get<Car[]>('/sl/projection/cars')
    if (Array.isArray(data) && data.length > 0) return data
    const fallback = await listCarsFromReflection()
    if (fallback.length > 0) return fallback
    return Array.isArray(data) ? data : []
  } catch {
    return listCarsFromReflection()
  }
}

export async function listMissions(): Promise<Mission[]> {
  if (MOCK) return mockMissions()
  try {
    const { data } = await http.get<Mission[]>('/sl/projection/missions')
    if (Array.isArray(data) && data.length > 0) return data
    const fallback = await listMissionsFromReflection()
    if (fallback.length > 0) return fallback
    return Array.isArray(data) ? data : []
  } catch {
    return listMissionsFromReflection()
  }
}
