/**
 * Proto Loader for Clawx gRPC Services
 *
 * Loads clawx.proto at runtime using @grpc/proto-loader.
 * Provides typed service definitions for server and client use.
 */
import * as grpc from '@grpc/grpc-js';
import * as protoLoader from '@grpc/proto-loader';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { accessSync } from 'fs';
let cachedDefinition = null;
function getProtoPath() {
    // __dirname equivalent for ESM
    const currentFile = fileURLToPath(import.meta.url);
    const currentDir = dirname(currentFile);
    // In compiled JS, this file is at dist/core/grpc/proto-loader.js
    // The proto file should be copied to dist/core/grpc/clawx.proto
    // But proto-loader works with the source proto file directly
    // Try compiled location first, then source
    const candidates = [
        join(currentDir, 'clawx.proto'), // Same dir (works in both src and dist)
        join(currentDir, '..', '..', '..', 'src', 'core', 'grpc', 'clawx.proto'), // From dist back to src
    ];
    for (const candidate of candidates) {
        try {
            accessSync(candidate);
            return candidate;
        }
        catch { }
    }
    // Fallback — return the first candidate and let proto-loader error with a clear path
    return candidates[0];
}
/**
 * Load the Clawx proto definition. Cached after first load.
 */
export function loadClawxProto() {
    if (cachedDefinition)
        return cachedDefinition;
    const protoPath = getProtoPath();
    const packageDefinition = protoLoader.loadSync(protoPath, {
        keepCase: false, // Convert snake_case to camelCase
        longs: Number, // int64 as JS number
        enums: String, // Enums as strings
        bytes: Buffer, // bytes as Buffer
        defaults: true, // Include default values
        oneofs: true,
    });
    cachedDefinition = grpc.loadPackageDefinition(packageDefinition);
    return cachedDefinition;
}
/**
 * Get the ClawxAgentService definition for server or client use.
 */
export function getAgentServiceDefinition() {
    const proto = loadClawxProto();
    return proto.clawx.ClawxAgentService;
}
/**
 * Get the Health service definition.
 */
export function getHealthServiceDefinition() {
    const proto = loadClawxProto();
    return proto.clawx.Health;
}
/**
 * Encode a payload object to protobuf bytes field (JSON in Buffer).
 */
export function encodePayload(obj) {
    if (obj === undefined || obj === null)
        return Buffer.alloc(0);
    return Buffer.from(JSON.stringify(obj));
}
/**
 * Decode a protobuf bytes field back to an object.
 */
export function decodePayload(buf) {
    if (!buf || buf.length === 0)
        return undefined;
    const str = Buffer.isBuffer(buf) ? buf.toString('utf8') : Buffer.from(buf).toString('utf8');
    if (!str)
        return undefined;
    try {
        return JSON.parse(str);
    }
    catch {
        return str;
    }
}
//# sourceMappingURL=proto-loader.js.map