import path from 'path';
import { fileURLToPath } from 'url';
import grpc from '@grpc/grpc-js'
import protoLoader from '@grpc/proto-loader'

export const __filename = fileURLToPath(import.meta.url)
export const __dirname = path.dirname(__filename)


// ========== 加载 Proto ==========
const PROTO_ROOT = path.resolve(__dirname, './proto')              // 指向 server/proto/
const AGV_PROTO_ENTRY = path.join(PROTO_ROOT, 'cmvr/api/agv_service.proto')
const ARM_PROTO_ENTRY = path.join(PROTO_ROOT, 'cmvr/api/arm_service.proto')

const agvPackageDefinition = protoLoader.loadSync(
  AGV_PROTO_ENTRY,
  {
    includeDirs: [PROTO_ROOT , path.join(PROTO_ROOT, 'cmvr/api')],    // 关键：让加载器从 PROTO_ROOT 查找 import
    keepCase: true,
    longs: String,
    enums: String,
    defaults: true,
    oneofs: true
  }
)

const armPackageDefinition = protoLoader.loadSync(
  ARM_PROTO_ENTRY,
  {
    includeDirs: [PROTO_ROOT , path.join(PROTO_ROOT, 'cmvr/api')],    // 关键：让加载器从 PROTO_ROOT 查找 import
    keepCase: true,
    longs: String,
    enums: String,
    defaults: true,
    oneofs: true
  }
)

const agvProto = grpc.loadPackageDefinition(agvPackageDefinition).cmvr.api
const armProto = grpc.loadPackageDefinition(armPackageDefinition).cmvr.api

export const createAGVGrpcClient = (address) => {
  const grpcClient = new agvProto.AgvService(
    address,
    grpc.credentials.createInsecure()
  )
  return grpcClient
}

export const createARMGrpcClient = (address) => {
  const grpcClient = new armProto.ArmService(
    address,
    grpc.credentials.createInsecure()
  )
  return grpcClient
}