/*
 * ============================================================
 * OTLP kvlistValue parsing helpers
 * ============================================================
 */
/**
 * Extract a value from an OTLP kvlistValue by key.
 * Returns the string/int value or nested kvlistValue as JSONObject.
 */
export function getKvValue(kvList, key) {
    if (!kvList) {
        return null;
    }
    const values = kvList["values"];
    if (!values) {
        return null;
    }
    for (const entry of values) {
        if (entry["key"] === key) {
            const val = entry["value"];
            if (!val) {
                return null;
            }
            // Handle both camelCase (JSON encoding) and snake_case (protobuf via protobufjs)
            if (val["stringValue"] !== undefined) {
                return val["stringValue"];
            }
            if (val["string_value"] !== undefined) {
                return val["string_value"];
            }
            if (val["intValue"] !== undefined) {
                return String(val["intValue"]);
            }
            if (val["int_value"] !== undefined) {
                return String(val["int_value"]);
            }
            if (val["boolValue"] !== undefined) {
                return String(val["boolValue"]);
            }
            if (val["bool_value"] !== undefined) {
                return String(val["bool_value"]);
            }
            if (val["kvlistValue"]) {
                return val["kvlistValue"];
            }
            if (val["kvlist_value"]) {
                return val["kvlist_value"];
            }
            if (val["arrayValue"]) {
                return val["arrayValue"];
            }
            if (val["array_value"]) {
                return val["array_value"];
            }
            return null;
        }
    }
    return null;
}
/**
 * Extract a string value from an OTLP kvlistValue by key.
 */
export function getKvStringValue(kvList, key) {
    const val = getKvValue(kvList, key);
    if (typeof val === "string") {
        return val;
    }
    return "";
}
/**
 * Extract a nested kvlist value (parent → child).
 */
export function getNestedKvValue(kvList, parentKey, childKey) {
    const parent = getKvValue(kvList, parentKey);
    if (!parent || typeof parent === "string") {
        return "";
    }
    return getKvStringValue(parent, childKey);
}
/**
 * Convert a kvlistValue to a flat Record<string, string> (for labels, annotations, env).
 */
export function getKvListAsRecord(kvList) {
    const result = {};
    if (!kvList) {
        return result;
    }
    const values = kvList["values"];
    if (!values) {
        return result;
    }
    for (const entry of values) {
        const key = entry["key"] || "";
        const val = entry["value"];
        if (key && val) {
            if (val["stringValue"] !== undefined) {
                result[key] = val["stringValue"];
            }
            else if (val["string_value"] !== undefined) {
                result[key] = val["string_value"];
            }
            else if (val["intValue"] !== undefined) {
                result[key] = String(val["intValue"]);
            }
            else if (val["int_value"] !== undefined) {
                result[key] = String(val["int_value"]);
            }
            else if (val["boolValue"] !== undefined) {
                result[key] = String(val["boolValue"]);
            }
            else if (val["bool_value"] !== undefined) {
                result[key] = String(val["bool_value"]);
            }
        }
    }
    return result;
}
/**
 * Convert an OTLP arrayValue to an array of JSONObjects (kvlistValues).
 */
export function getArrayValues(arrayValue) {
    if (!arrayValue) {
        return [];
    }
    const values = arrayValue["values"];
    if (!values) {
        return [];
    }
    return values
        .map((item) => {
        if (item["kvlistValue"]) {
            return item["kvlistValue"];
        }
        if (item["kvlist_value"]) {
            return item["kvlist_value"];
        }
        if (item["stringValue"]) {
            return item;
        }
        if (item["string_value"]) {
            return item;
        }
        return null;
    })
        .filter(Boolean);
}
/**
 * Recursively convert an OTLP value wrapper to a plain JavaScript value.
 * Handles stringValue, intValue, boolValue, kvlistValue, and arrayValue.
 */
function convertOtlpValue(valueWrapper) {
    // Handle both camelCase (JSON encoding) and snake_case (protobuf via protobufjs)
    if (valueWrapper["stringValue"] !== undefined) {
        return valueWrapper["stringValue"];
    }
    if (valueWrapper["string_value"] !== undefined) {
        return valueWrapper["string_value"];
    }
    if (valueWrapper["intValue"] !== undefined) {
        return Number(valueWrapper["intValue"]);
    }
    if (valueWrapper["int_value"] !== undefined) {
        return Number(valueWrapper["int_value"]);
    }
    if (valueWrapper["boolValue"] !== undefined) {
        return valueWrapper["boolValue"];
    }
    if (valueWrapper["bool_value"] !== undefined) {
        return valueWrapper["bool_value"];
    }
    if (valueWrapper["doubleValue"] !== undefined) {
        return Number(valueWrapper["doubleValue"]);
    }
    if (valueWrapper["double_value"] !== undefined) {
        return Number(valueWrapper["double_value"]);
    }
    if (valueWrapper["kvlistValue"]) {
        return kvListToPlainObject(valueWrapper["kvlistValue"]);
    }
    if (valueWrapper["kvlist_value"]) {
        return kvListToPlainObject(valueWrapper["kvlist_value"]);
    }
    if (valueWrapper["arrayValue"]) {
        return convertOtlpArray(valueWrapper["arrayValue"]);
    }
    if (valueWrapper["array_value"]) {
        return convertOtlpArray(valueWrapper["array_value"]);
    }
    return null;
}
/**
 * Convert an OTLP arrayValue to a plain JavaScript array.
 */
function convertOtlpArray(arrayValue) {
    const values = arrayValue["values"];
    if (!values) {
        return [];
    }
    return values.map((item) => {
        // Each item in arrayValue.values is a value wrapper
        return convertOtlpValue(item);
    });
}
/**
 * Convert an OTLP kvlistValue (nested key-value structure) to a plain
 * JavaScript object. This preserves the full original K8s manifest structure.
 */
export function kvListToPlainObject(kvList) {
    const result = {};
    if (!kvList) {
        return result;
    }
    const values = kvList["values"];
    if (!values) {
        return result;
    }
    for (const entry of values) {
        const key = entry["key"] || "";
        const val = entry["value"];
        if (key && val) {
            result[key] = convertOtlpValue(val);
        }
    }
    return result;
}
/*
 * ============================================================
 * Parsers
 * ============================================================
 */
function parseMetadata(kvList) {
    const labelsKvList = getKvValue(kvList, "labels");
    const annotationsKvList = getKvValue(kvList, "annotations");
    const ownerRefsArrayValue = getKvValue(kvList, "ownerReferences");
    const ownerReferences = [];
    if (ownerRefsArrayValue && typeof ownerRefsArrayValue !== "string") {
        const refs = getArrayValues(ownerRefsArrayValue);
        for (const ref of refs) {
            ownerReferences.push({
                kind: getKvStringValue(ref, "kind"),
                name: getKvStringValue(ref, "name"),
                uid: getKvStringValue(ref, "uid"),
            });
        }
    }
    return {
        name: getKvStringValue(kvList, "name"),
        namespace: getKvStringValue(kvList, "namespace"),
        uid: getKvStringValue(kvList, "uid"),
        creationTimestamp: getKvStringValue(kvList, "creationTimestamp"),
        labels: labelsKvList && typeof labelsKvList !== "string"
            ? getKvListAsRecord(labelsKvList)
            : {},
        annotations: annotationsKvList && typeof annotationsKvList !== "string"
            ? getKvListAsRecord(annotationsKvList)
            : {},
        ownerReferences,
    };
}
function parseContainerEnv(envArrayValue) {
    if (!envArrayValue || typeof envArrayValue === "string") {
        return [];
    }
    const envItems = getArrayValues(envArrayValue);
    const result = [];
    for (const envKvList of envItems) {
        const name = getKvStringValue(envKvList, "name");
        const directValue = getKvStringValue(envKvList, "value");
        if (directValue) {
            result.push({ name, value: directValue });
        }
        else {
            // Check for valueFrom (secretKeyRef, configMapKeyRef, fieldRef)
            const valueFrom = getKvValue(envKvList, "valueFrom");
            if (valueFrom && typeof valueFrom !== "string") {
                const secretRef = getKvValue(valueFrom, "secretKeyRef");
                const configMapRef = getKvValue(valueFrom, "configMapKeyRef");
                const fieldRef = getKvValue(valueFrom, "fieldRef");
                if (secretRef && typeof secretRef !== "string") {
                    const secretName = getKvStringValue(secretRef, "name");
                    const secretKey = getKvStringValue(secretRef, "key");
                    result.push({
                        name,
                        value: `<Secret: ${secretName}/${secretKey}>`,
                    });
                }
                else if (configMapRef && typeof configMapRef !== "string") {
                    const cmName = getKvStringValue(configMapRef, "name");
                    const cmKey = getKvStringValue(configMapRef, "key");
                    result.push({
                        name,
                        value: `<ConfigMap: ${cmName}/${cmKey}>`,
                    });
                }
                else if (fieldRef && typeof fieldRef !== "string") {
                    const fieldPath = getKvStringValue(fieldRef, "fieldPath");
                    result.push({ name, value: `<FieldRef: ${fieldPath}>` });
                }
                else {
                    result.push({ name, value: "<from valueFrom>" });
                }
            }
            else {
                result.push({ name, value: directValue || "" });
            }
        }
    }
    return result;
}
function parseContainerSpec(kvList) {
    const portsArrayValue = getKvValue(kvList, "ports");
    const ports = [];
    if (portsArrayValue && typeof portsArrayValue !== "string") {
        const portItems = getArrayValues(portsArrayValue);
        for (const portKv of portItems) {
            ports.push({
                name: getKvStringValue(portKv, "name"),
                containerPort: parseInt(getKvStringValue(portKv, "containerPort")) || 0,
                protocol: getKvStringValue(portKv, "protocol") || "TCP",
            });
        }
    }
    const envArrayValue = getKvValue(kvList, "env");
    const env = parseContainerEnv(envArrayValue);
    const volumeMountsArray = getKvValue(kvList, "volumeMounts");
    const volumeMounts = [];
    if (volumeMountsArray && typeof volumeMountsArray !== "string") {
        const mountItems = getArrayValues(volumeMountsArray);
        for (const mountKv of mountItems) {
            volumeMounts.push({
                name: getKvStringValue(mountKv, "name"),
                mountPath: getKvStringValue(mountKv, "mountPath"),
                readOnly: getKvStringValue(mountKv, "readOnly") === "true",
            });
        }
    }
    const resourcesKv = getKvValue(kvList, "resources");
    let requests = {};
    let limits = {};
    if (resourcesKv && typeof resourcesKv !== "string") {
        const reqKv = getKvValue(resourcesKv, "requests");
        const limKv = getKvValue(resourcesKv, "limits");
        if (reqKv && typeof reqKv !== "string") {
            requests = getKvListAsRecord(reqKv);
        }
        if (limKv && typeof limKv !== "string") {
            limits = getKvListAsRecord(limKv);
        }
    }
    const commandArray = getKvValue(kvList, "command");
    const command = [];
    if (commandArray && typeof commandArray !== "string") {
        const cmdValues = commandArray["values"] || [];
        for (const v of cmdValues) {
            if (v["stringValue"]) {
                command.push(v["stringValue"]);
            }
        }
    }
    const argsArray = getKvValue(kvList, "args");
    const args = [];
    if (argsArray && typeof argsArray !== "string") {
        const argValues = argsArray["values"] || [];
        for (const v of argValues) {
            if (v["stringValue"]) {
                args.push(v["stringValue"]);
            }
        }
    }
    return {
        name: getKvStringValue(kvList, "name"),
        image: getKvStringValue(kvList, "image"),
        command,
        args,
        env,
        ports,
        resources: { requests, limits },
        volumeMounts,
    };
}
function parseConditions(conditionsArrayValue) {
    if (!conditionsArrayValue) {
        return [];
    }
    const items = getArrayValues(conditionsArrayValue);
    return items.map((kvList) => {
        return {
            type: getKvStringValue(kvList, "type"),
            status: getKvStringValue(kvList, "status"),
            reason: getKvStringValue(kvList, "reason"),
            message: getKvStringValue(kvList, "message"),
            lastTransitionTime: getKvStringValue(kvList, "lastTransitionTime"),
        };
    });
}
function parseContainerStatuses(statusesArrayValue) {
    if (!statusesArrayValue) {
        return [];
    }
    const items = getArrayValues(statusesArrayValue);
    return items.map((kvList) => {
        // state is a kvlist with one key (running/waiting/terminated)
        const stateKv = getKvValue(kvList, "state");
        let state = "Unknown";
        let reason = "";
        if (stateKv && typeof stateKv !== "string") {
            const stateValues = stateKv["values"];
            if (stateValues && stateValues.length > 0 && stateValues[0]) {
                state = stateValues[0]["key"] || "Unknown";
                // Extract reason from the state's nested kvlist value (e.g., waiting -> { reason: "CrashLoopBackOff" })
                const stateDetail = stateValues[0]["value"];
                if (stateDetail && stateDetail["kvlistValue"]) {
                    reason = getKvStringValue(stateDetail["kvlistValue"], "reason");
                }
            }
        }
        return {
            name: getKvStringValue(kvList, "name"),
            ready: getKvStringValue(kvList, "ready") === "true",
            restartCount: parseInt(getKvStringValue(kvList, "restartCount")) || 0,
            state,
            reason,
            image: getKvStringValue(kvList, "image"),
        };
    });
}
/**
 * Parse a raw OTLP log body into a Pod object.
 * The body format: { kvlistValue: { values: [{ key: "type", value: ... }, { key: "object", value: { kvlistValue: ... } }] } }
 */
export function parsePodObject(objectKvList) {
    try {
        const metadataKv = getKvValue(objectKvList, "metadata");
        if (!metadataKv || typeof metadataKv === "string") {
            return null;
        }
        const metadata = parseMetadata(metadataKv);
        const specKv = getKvValue(objectKvList, "spec");
        const statusKv = getKvValue(objectKvList, "status");
        // Parse containers
        const containers = [];
        const initContainers = [];
        if (specKv && typeof specKv !== "string") {
            const containersArray = getKvValue(specKv, "containers");
            if (containersArray && typeof containersArray !== "string") {
                const containerItems = getArrayValues(containersArray);
                for (const cKv of containerItems) {
                    containers.push(parseContainerSpec(cKv));
                }
            }
            const initContainersArray = getKvValue(specKv, "initContainers");
            if (initContainersArray && typeof initContainersArray !== "string") {
                const initItems = getArrayValues(initContainersArray);
                for (const cKv of initItems) {
                    initContainers.push(parseContainerSpec(cKv));
                }
            }
        }
        // Parse volumes
        const volumes = [];
        if (specKv && typeof specKv !== "string") {
            const volumesArray = getKvValue(specKv, "volumes");
            if (volumesArray && typeof volumesArray !== "string") {
                const volItems = getArrayValues(volumesArray);
                for (const volKv of volItems) {
                    const name = getKvStringValue(volKv, "name");
                    // Volume type is one of: configMap, secret, emptyDir, hostPath, persistentVolumeClaim, etc.
                    const volValues = volKv["values"];
                    let volType = "unknown";
                    let volSource = "";
                    if (volValues) {
                        for (const v of volValues) {
                            const k = v["key"] || "";
                            if (k !== "name") {
                                volType = k;
                                const innerVal = v["value"];
                                if (innerVal && innerVal["kvlistValue"]) {
                                    const innerKv = innerVal["kvlistValue"];
                                    volSource =
                                        getKvStringValue(innerKv, "name") ||
                                            getKvStringValue(innerKv, "path") ||
                                            getKvStringValue(innerKv, "claimName") ||
                                            volType;
                                }
                                break;
                            }
                        }
                    }
                    volumes.push({ name, type: volType, source: volSource });
                }
            }
        }
        // Parse tolerations
        const tolerations = [];
        if (specKv && typeof specKv !== "string") {
            const tolArray = getKvValue(specKv, "tolerations");
            if (tolArray && typeof tolArray !== "string") {
                const tolItems = getArrayValues(tolArray);
                for (const tolKv of tolItems) {
                    tolerations.push({
                        key: getKvStringValue(tolKv, "key"),
                        operator: getKvStringValue(tolKv, "operator"),
                        value: getKvStringValue(tolKv, "value"),
                        effect: getKvStringValue(tolKv, "effect"),
                    });
                }
            }
        }
        // Parse nodeSelector
        let nodeSelector = {};
        if (specKv && typeof specKv !== "string") {
            const nsKv = getKvValue(specKv, "nodeSelector");
            if (nsKv && typeof nsKv !== "string") {
                nodeSelector = getKvListAsRecord(nsKv);
            }
        }
        // Parse status
        let phase = "";
        let podIP = "";
        let hostIP = "";
        let qosClass = "";
        let conditions = [];
        let containerStatuses = [];
        let initContainerStatuses = [];
        if (statusKv && typeof statusKv !== "string") {
            phase = getKvStringValue(statusKv, "phase");
            podIP = getKvStringValue(statusKv, "podIP");
            hostIP = getKvStringValue(statusKv, "hostIP");
            qosClass = getKvStringValue(statusKv, "qosClass");
            const condArray = getKvValue(statusKv, "conditions");
            conditions = parseConditions(condArray);
            const csArray = getKvValue(statusKv, "containerStatuses");
            containerStatuses = parseContainerStatuses(csArray);
            const icsArray = getKvValue(statusKv, "initContainerStatuses");
            initContainerStatuses = parseContainerStatuses(icsArray);
        }
        return {
            metadata,
            spec: {
                containers,
                initContainers,
                serviceAccountName: specKv
                    ? getKvStringValue(specKv, "serviceAccountName")
                    : "",
                nodeName: specKv
                    ? getKvStringValue(specKv, "nodeName")
                    : "",
                nodeSelector,
                tolerations,
                volumes,
            },
            status: {
                phase,
                podIP,
                hostIP,
                qosClass,
                conditions,
                containerStatuses,
                initContainerStatuses,
            },
        };
    }
    catch (_a) {
        return null;
    }
}
export function parseNodeObject(objectKvList) {
    try {
        const metadataKv = getKvValue(objectKvList, "metadata");
        if (!metadataKv || typeof metadataKv === "string") {
            return null;
        }
        const statusKv = getKvValue(objectKvList, "status");
        let conditions = [];
        let nodeInfo = {
            osImage: "",
            kernelVersion: "",
            containerRuntimeVersion: "",
            kubeletVersion: "",
            architecture: "",
            operatingSystem: "",
        };
        let allocatable = {};
        let capacity = {};
        let addresses = [];
        if (statusKv && typeof statusKv !== "string") {
            const condArray = getKvValue(statusKv, "conditions");
            conditions = parseConditions(condArray);
            const nodeInfoKv = getKvValue(statusKv, "nodeInfo");
            if (nodeInfoKv && typeof nodeInfoKv !== "string") {
                nodeInfo = {
                    osImage: getKvStringValue(nodeInfoKv, "osImage"),
                    kernelVersion: getKvStringValue(nodeInfoKv, "kernelVersion"),
                    containerRuntimeVersion: getKvStringValue(nodeInfoKv, "containerRuntimeVersion"),
                    kubeletVersion: getKvStringValue(nodeInfoKv, "kubeletVersion"),
                    architecture: getKvStringValue(nodeInfoKv, "architecture"),
                    operatingSystem: getKvStringValue(nodeInfoKv, "operatingSystem"),
                };
            }
            const allocKv = getKvValue(statusKv, "allocatable");
            if (allocKv && typeof allocKv !== "string") {
                allocatable = getKvListAsRecord(allocKv);
            }
            const capKv = getKvValue(statusKv, "capacity");
            if (capKv && typeof capKv !== "string") {
                capacity = getKvListAsRecord(capKv);
            }
            const addrArray = getKvValue(statusKv, "addresses");
            if (addrArray && typeof addrArray !== "string") {
                const addrItems = getArrayValues(addrArray);
                addresses = addrItems.map((a) => {
                    return {
                        type: getKvStringValue(a, "type"),
                        address: getKvStringValue(a, "address"),
                    };
                });
            }
        }
        return {
            metadata: parseMetadata(metadataKv),
            status: {
                conditions,
                nodeInfo,
                allocatable,
                capacity,
                addresses,
            },
        };
    }
    catch (_a) {
        return null;
    }
}
export function parseDeploymentObject(objectKvList) {
    try {
        const metadataKv = getKvValue(objectKvList, "metadata");
        if (!metadataKv || typeof metadataKv === "string") {
            return null;
        }
        const specKv = getKvValue(objectKvList, "spec");
        const statusKv = getKvValue(objectKvList, "status");
        let replicas = 0;
        let strategy = "";
        let selector = {};
        if (specKv && typeof specKv !== "string") {
            replicas = parseInt(getKvStringValue(specKv, "replicas")) || 0;
            const strategyKv = getKvValue(specKv, "strategy");
            if (strategyKv && typeof strategyKv !== "string") {
                strategy = getKvStringValue(strategyKv, "type");
            }
            const selectorKv = getKvValue(specKv, "selector");
            if (selectorKv && typeof selectorKv !== "string") {
                const matchLabelsKv = getKvValue(selectorKv, "matchLabels");
                if (matchLabelsKv && typeof matchLabelsKv !== "string") {
                    selector = getKvListAsRecord(matchLabelsKv);
                }
            }
        }
        let statusReplicas = 0;
        let readyReplicas = 0;
        let availableReplicas = 0;
        let unavailableReplicas = 0;
        let conditions = [];
        if (statusKv && typeof statusKv !== "string") {
            statusReplicas = parseInt(getKvStringValue(statusKv, "replicas")) || 0;
            readyReplicas =
                parseInt(getKvStringValue(statusKv, "readyReplicas")) || 0;
            availableReplicas =
                parseInt(getKvStringValue(statusKv, "availableReplicas")) || 0;
            unavailableReplicas =
                parseInt(getKvStringValue(statusKv, "unavailableReplicas")) || 0;
            const condArray = getKvValue(statusKv, "conditions");
            conditions = parseConditions(condArray);
        }
        return {
            metadata: parseMetadata(metadataKv),
            spec: { replicas, strategy, selector },
            status: {
                replicas: statusReplicas,
                readyReplicas,
                availableReplicas,
                unavailableReplicas,
                conditions,
            },
        };
    }
    catch (_a) {
        return null;
    }
}
export function parseStatefulSetObject(objectKvList) {
    try {
        const metadataKv = getKvValue(objectKvList, "metadata");
        if (!metadataKv || typeof metadataKv === "string") {
            return null;
        }
        const specKv = getKvValue(objectKvList, "spec");
        const statusKv = getKvValue(objectKvList, "status");
        let replicas = 0;
        let serviceName = "";
        let podManagementPolicy = "";
        let updateStrategy = "";
        if (specKv && typeof specKv !== "string") {
            replicas = parseInt(getKvStringValue(specKv, "replicas")) || 0;
            serviceName = getKvStringValue(specKv, "serviceName");
            podManagementPolicy = getKvStringValue(specKv, "podManagementPolicy");
            const usKv = getKvValue(specKv, "updateStrategy");
            if (usKv && typeof usKv !== "string") {
                updateStrategy = getKvStringValue(usKv, "type");
            }
        }
        return {
            metadata: parseMetadata(metadataKv),
            spec: { replicas, serviceName, podManagementPolicy, updateStrategy },
            status: {
                replicas: statusKv
                    ? parseInt(getKvStringValue(statusKv, "replicas")) || 0
                    : 0,
                readyReplicas: statusKv
                    ? parseInt(getKvStringValue(statusKv, "readyReplicas")) || 0
                    : 0,
                currentReplicas: statusKv
                    ? parseInt(getKvStringValue(statusKv, "currentReplicas")) || 0
                    : 0,
            },
        };
    }
    catch (_a) {
        return null;
    }
}
export function parseDaemonSetObject(objectKvList) {
    try {
        const metadataKv = getKvValue(objectKvList, "metadata");
        if (!metadataKv || typeof metadataKv === "string") {
            return null;
        }
        const specKv = getKvValue(objectKvList, "spec");
        const statusKv = getKvValue(objectKvList, "status");
        let updateStrategy = "";
        if (specKv && typeof specKv !== "string") {
            const usKv = getKvValue(specKv, "updateStrategy");
            if (usKv && typeof usKv !== "string") {
                updateStrategy = getKvStringValue(usKv, "type");
            }
        }
        return {
            metadata: parseMetadata(metadataKv),
            spec: { updateStrategy },
            status: {
                desiredNumberScheduled: statusKv
                    ? parseInt(getKvStringValue(statusKv, "desiredNumberScheduled")) || 0
                    : 0,
                currentNumberScheduled: statusKv
                    ? parseInt(getKvStringValue(statusKv, "currentNumberScheduled")) || 0
                    : 0,
                numberReady: statusKv
                    ? parseInt(getKvStringValue(statusKv, "numberReady")) ||
                        0
                    : 0,
                numberMisscheduled: statusKv
                    ? parseInt(getKvStringValue(statusKv, "numberMisscheduled")) || 0
                    : 0,
                numberAvailable: statusKv
                    ? parseInt(getKvStringValue(statusKv, "numberAvailable")) || 0
                    : 0,
            },
        };
    }
    catch (_a) {
        return null;
    }
}
export function parseJobObject(objectKvList) {
    try {
        const metadataKv = getKvValue(objectKvList, "metadata");
        if (!metadataKv || typeof metadataKv === "string") {
            return null;
        }
        const specKv = getKvValue(objectKvList, "spec");
        const statusKv = getKvValue(objectKvList, "status");
        return {
            metadata: parseMetadata(metadataKv),
            spec: {
                completions: specKv
                    ? parseInt(getKvStringValue(specKv, "completions")) || 0
                    : 0,
                parallelism: specKv
                    ? parseInt(getKvStringValue(specKv, "parallelism")) || 0
                    : 0,
                backoffLimit: specKv
                    ? parseInt(getKvStringValue(specKv, "backoffLimit")) ||
                        0
                    : 0,
            },
            status: {
                active: statusKv
                    ? parseInt(getKvStringValue(statusKv, "active")) || 0
                    : 0,
                succeeded: statusKv
                    ? parseInt(getKvStringValue(statusKv, "succeeded")) || 0
                    : 0,
                failed: statusKv
                    ? parseInt(getKvStringValue(statusKv, "failed")) || 0
                    : 0,
                startTime: statusKv
                    ? getKvStringValue(statusKv, "startTime")
                    : "",
                completionTime: statusKv
                    ? getKvStringValue(statusKv, "completionTime")
                    : "",
                conditions: statusKv
                    ? parseConditions(getKvValue(statusKv, "conditions"))
                    : [],
            },
        };
    }
    catch (_a) {
        return null;
    }
}
export function parseCronJobObject(objectKvList) {
    try {
        const metadataKv = getKvValue(objectKvList, "metadata");
        if (!metadataKv || typeof metadataKv === "string") {
            return null;
        }
        const specKv = getKvValue(objectKvList, "spec");
        const statusKv = getKvValue(objectKvList, "status");
        return {
            metadata: parseMetadata(metadataKv),
            spec: {
                schedule: specKv
                    ? getKvStringValue(specKv, "schedule")
                    : "",
                suspend: specKv
                    ? getKvStringValue(specKv, "suspend") === "true"
                    : false,
                concurrencyPolicy: specKv
                    ? getKvStringValue(specKv, "concurrencyPolicy")
                    : "",
                successfulJobsHistoryLimit: specKv
                    ? parseInt(getKvStringValue(specKv, "successfulJobsHistoryLimit")) || 0
                    : 0,
                failedJobsHistoryLimit: specKv
                    ? parseInt(getKvStringValue(specKv, "failedJobsHistoryLimit")) || 0
                    : 0,
            },
            status: {
                lastScheduleTime: statusKv
                    ? getKvStringValue(statusKv, "lastScheduleTime")
                    : "",
                activeCount: statusKv
                    ? parseInt(getKvStringValue(statusKv, "active")) || 0
                    : 0,
            },
        };
    }
    catch (_a) {
        return null;
    }
}
export function parseNamespaceObject(objectKvList) {
    try {
        const metadataKv = getKvValue(objectKvList, "metadata");
        if (!metadataKv || typeof metadataKv === "string") {
            return null;
        }
        const statusKv = getKvValue(objectKvList, "status");
        return {
            metadata: parseMetadata(metadataKv),
            status: {
                phase: statusKv
                    ? getKvStringValue(statusKv, "phase")
                    : "",
            },
        };
    }
    catch (_a) {
        return null;
    }
}
export function parsePVCObject(objectKvList) {
    try {
        const metadataKv = getKvValue(objectKvList, "metadata");
        if (!metadataKv || typeof metadataKv === "string") {
            return null;
        }
        const metadata = parseMetadata(metadataKv);
        if (!metadata.name) {
            return null;
        }
        const specKv = getKvValue(objectKvList, "spec");
        const statusKv = getKvValue(objectKvList, "status");
        // Parse spec
        const accessModes = [];
        let storageClassName = "";
        let volumeName = "";
        let requestsStorage = "";
        if (specKv && typeof specKv !== "string") {
            storageClassName = getKvStringValue(specKv, "storageClassName");
            volumeName = getKvStringValue(specKv, "volumeName");
            const accessModesArray = getKvValue(specKv, "accessModes");
            if (accessModesArray && typeof accessModesArray !== "string") {
                const modeValues = accessModesArray["values"] || [];
                for (const v of modeValues) {
                    if (v["stringValue"]) {
                        accessModes.push(v["stringValue"]);
                    }
                }
            }
            const resourcesKv = getKvValue(specKv, "resources");
            if (resourcesKv && typeof resourcesKv !== "string") {
                requestsStorage = getNestedKvValue(resourcesKv, "requests", "storage");
            }
        }
        // Parse status
        let phase = "";
        let capacityStorage = "";
        if (statusKv && typeof statusKv !== "string") {
            phase = getKvStringValue(statusKv, "phase");
            capacityStorage = getNestedKvValue(statusKv, "capacity", "storage");
        }
        return {
            metadata,
            spec: {
                accessModes,
                storageClassName,
                volumeName,
                resources: {
                    requests: {
                        storage: requestsStorage,
                    },
                },
            },
            status: {
                phase,
                capacity: {
                    storage: capacityStorage,
                },
            },
        };
    }
    catch (_a) {
        return null;
    }
}
export function parsePVObject(objectKvList) {
    try {
        const metadataKv = getKvValue(objectKvList, "metadata");
        if (!metadataKv || typeof metadataKv === "string") {
            return null;
        }
        const metadata = parseMetadata(metadataKv);
        if (!metadata.name) {
            return null;
        }
        const specKv = getKvValue(objectKvList, "spec");
        const statusKv = getKvValue(objectKvList, "status");
        // Parse spec
        let capacityStorage = "";
        const accessModes = [];
        let storageClassName = "";
        let persistentVolumeReclaimPolicy = "";
        let claimRefName = "";
        let claimRefNamespace = "";
        if (specKv && typeof specKv !== "string") {
            capacityStorage = getNestedKvValue(specKv, "capacity", "storage");
            storageClassName = getKvStringValue(specKv, "storageClassName");
            persistentVolumeReclaimPolicy = getKvStringValue(specKv, "persistentVolumeReclaimPolicy");
            const accessModesArray = getKvValue(specKv, "accessModes");
            if (accessModesArray && typeof accessModesArray !== "string") {
                const modeValues = accessModesArray["values"] || [];
                for (const v of modeValues) {
                    if (v["stringValue"]) {
                        accessModes.push(v["stringValue"]);
                    }
                }
            }
            const claimRefKv = getKvValue(specKv, "claimRef");
            if (claimRefKv && typeof claimRefKv !== "string") {
                claimRefName = getKvStringValue(claimRefKv, "name");
                claimRefNamespace = getKvStringValue(claimRefKv, "namespace");
            }
        }
        // Parse status
        let phase = "";
        if (statusKv && typeof statusKv !== "string") {
            phase = getKvStringValue(statusKv, "phase");
        }
        return {
            metadata,
            spec: {
                capacity: {
                    storage: capacityStorage,
                },
                accessModes,
                storageClassName,
                persistentVolumeReclaimPolicy,
                claimRef: {
                    name: claimRefName,
                    namespace: claimRefNamespace,
                },
            },
            status: {
                phase,
            },
        };
    }
    catch (_a) {
        return null;
    }
}
export function parseHPAObject(objectKvList) {
    try {
        const metadataKv = getKvValue(objectKvList, "metadata");
        if (!metadataKv || typeof metadataKv === "string") {
            return null;
        }
        const specKv = getKvValue(objectKvList, "spec");
        const statusKv = getKvValue(objectKvList, "status");
        let minReplicas = 0;
        let maxReplicas = 0;
        let scaleTargetRef = {
            kind: "",
            name: "",
        };
        const metrics = [];
        if (specKv && typeof specKv !== "string") {
            minReplicas = parseInt(getKvStringValue(specKv, "minReplicas")) || 0;
            maxReplicas = parseInt(getKvStringValue(specKv, "maxReplicas")) || 0;
            const targetRefKv = getKvValue(specKv, "scaleTargetRef");
            if (targetRefKv && typeof targetRefKv !== "string") {
                scaleTargetRef = {
                    kind: getKvStringValue(targetRefKv, "kind"),
                    name: getKvStringValue(targetRefKv, "name"),
                };
            }
            const metricsArrayKv = getKvValue(specKv, "metrics");
            if (metricsArrayKv && typeof metricsArrayKv !== "string") {
                const metricsItems = getArrayValues(metricsArrayKv);
                for (const metricKv of metricsItems) {
                    const metricType = getKvStringValue(metricKv, "type");
                    let resourceName = "";
                    let targetType = "";
                    let targetValue = "";
                    const resourceKv = getKvValue(metricKv, "resource");
                    if (resourceKv && typeof resourceKv !== "string") {
                        resourceName = getKvStringValue(resourceKv, "name");
                        const targetKv = getKvValue(resourceKv, "target");
                        if (targetKv && typeof targetKv !== "string") {
                            targetType = getKvStringValue(targetKv, "type");
                            targetValue =
                                getKvStringValue(targetKv, "averageUtilization") ||
                                    getKvStringValue(targetKv, "averageValue") ||
                                    getKvStringValue(targetKv, "value");
                        }
                    }
                    metrics.push({
                        type: metricType,
                        resourceName,
                        targetType,
                        targetValue,
                    });
                }
            }
        }
        let currentReplicas = 0;
        let desiredReplicas = 0;
        let conditions = [];
        if (statusKv && typeof statusKv !== "string") {
            currentReplicas =
                parseInt(getKvStringValue(statusKv, "currentReplicas")) || 0;
            desiredReplicas =
                parseInt(getKvStringValue(statusKv, "desiredReplicas")) || 0;
            const condArray = getKvValue(statusKv, "conditions");
            if (condArray && typeof condArray !== "string") {
                const condItems = getArrayValues(condArray);
                conditions = condItems.map((condKv) => {
                    return {
                        type: getKvStringValue(condKv, "type"),
                        status: getKvStringValue(condKv, "status"),
                        reason: getKvStringValue(condKv, "reason"),
                        message: getKvStringValue(condKv, "message"),
                        lastTransitionTime: getKvStringValue(condKv, "lastTransitionTime"),
                    };
                });
            }
        }
        return {
            metadata: parseMetadata(metadataKv),
            spec: { minReplicas, maxReplicas, scaleTargetRef, metrics },
            status: { currentReplicas, desiredReplicas, conditions },
        };
    }
    catch (_a) {
        return null;
    }
}
export function parseVPAObject(objectKvList) {
    try {
        const metadataKv = getKvValue(objectKvList, "metadata");
        if (!metadataKv || typeof metadataKv === "string") {
            return null;
        }
        const specKv = getKvValue(objectKvList, "spec");
        const statusKv = getKvValue(objectKvList, "status");
        let targetRef = { kind: "", name: "" };
        let updatePolicy = { updateMode: "" };
        let resourcePolicy = "";
        if (specKv && typeof specKv !== "string") {
            const targetRefKv = getKvValue(specKv, "targetRef");
            if (targetRefKv && typeof targetRefKv !== "string") {
                targetRef = {
                    kind: getKvStringValue(targetRefKv, "kind"),
                    name: getKvStringValue(targetRefKv, "name"),
                };
            }
            const updatePolicyKv = getKvValue(specKv, "updatePolicy");
            if (updatePolicyKv && typeof updatePolicyKv !== "string") {
                updatePolicy = {
                    updateMode: getKvStringValue(updatePolicyKv, "updateMode"),
                };
            }
            resourcePolicy = getKvStringValue(specKv, "resourcePolicy");
        }
        const containerRecommendations = [];
        if (statusKv && typeof statusKv !== "string") {
            const recommendationKv = getKvValue(statusKv, "recommendation");
            if (recommendationKv && typeof recommendationKv !== "string") {
                const containerRecsArrayKv = getKvValue(recommendationKv, "containerRecommendations");
                if (containerRecsArrayKv && typeof containerRecsArrayKv !== "string") {
                    const recItems = getArrayValues(containerRecsArrayKv);
                    for (const recKv of recItems) {
                        const targetKv = getKvValue(recKv, "target");
                        const lowerBoundKv = getKvValue(recKv, "lowerBound");
                        const upperBoundKv = getKvValue(recKv, "upperBound");
                        containerRecommendations.push({
                            containerName: getKvStringValue(recKv, "containerName"),
                            target: targetKv && typeof targetKv !== "string"
                                ? getKvListAsRecord(targetKv)
                                : {},
                            lowerBound: lowerBoundKv && typeof lowerBoundKv !== "string"
                                ? getKvListAsRecord(lowerBoundKv)
                                : {},
                            upperBound: upperBoundKv && typeof upperBoundKv !== "string"
                                ? getKvListAsRecord(upperBoundKv)
                                : {},
                        });
                    }
                }
            }
        }
        return {
            metadata: parseMetadata(metadataKv),
            spec: { targetRef, updatePolicy, resourcePolicy },
            status: {
                recommendation: { containerRecommendations },
            },
        };
    }
    catch (_a) {
        return null;
    }
}
/**
 * Extract the K8s object from a raw OTLP log body string.
 * For k8sobjects pull mode, the body is:
 * { kvlistValue: { values: [{ key: "type", value: ... }, { key: "object", value: { kvlistValue: ... } }] } }
 * OR for some modes, the object may be at the top level.
 */
export function extractObjectFromLogBody(bodyString) {
    try {
        const bodyObj = JSON.parse(bodyString);
        // Handle both camelCase (JSON encoding) and snake_case (protobuf via protobufjs)
        const topKvList = (bodyObj["kvlistValue"] ||
            bodyObj["kvlist_value"]);
        if (!topKvList) {
            return null;
        }
        // Try to get the "object" key (used in watch mode)
        const objectVal = getKvValue(topKvList, "object");
        if (objectVal && typeof objectVal !== "string") {
            return objectVal;
        }
        /*
         * If no "object" key, the kvlist might BE the object (pull mode)
         * Check if it has typical K8s fields
         */
        const kind = getKvValue(topKvList, "kind");
        if (kind) {
            return topKvList;
        }
        // Also check "metadata" as a fallback for objects without "kind"
        const metadata = getKvValue(topKvList, "metadata");
        if (metadata && typeof metadata !== "string") {
            return topKvList;
        }
        return null;
    }
    catch (_a) {
        return null;
    }
}
//# sourceMappingURL=KubernetesObjectParser.js.map