import { normalizeOpenCodeServerBaseUrlExplicit, readOpenCodeExplicitServerBaseUrl, } from '../providerSettings/definitions/opencode.js';
import { readSessionMetadataRuntimeDescriptor } from './agentRuntimeDescriptor.js';
function isRecord(value) {
    return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
function readLegacyOpenCodeBackendMode(metadata) {
    const backendModeRaw = typeof metadata.opencodeBackendMode === 'string'
        ? String(metadata.opencodeBackendMode).trim()
        : '';
    return backendModeRaw === 'server' ? 'server' : backendModeRaw === 'acp' ? 'acp' : null;
}
function readLegacyOpenCodeVendorSessionId(metadata) {
    const vendorSessionId = typeof metadata.opencodeSessionId === 'string'
        ? metadata.opencodeSessionId.trim()
        : '';
    return vendorSessionId || null;
}
export function readOpenCodeSessionAffinityFromMetadata(metadata) {
    if (!isRecord(metadata)) {
        return {
            backendMode: null,
            serverBaseUrl: null,
            serverBaseUrlExplicit: false,
        };
    }
    const runtimeDescriptor = readSessionMetadataRuntimeDescriptor(metadata, 'opencode');
    return {
        backendMode: runtimeDescriptor?.backendMode ?? readLegacyOpenCodeBackendMode(metadata),
        serverBaseUrl: runtimeDescriptor?.serverBaseUrl ?? readOpenCodeExplicitServerBaseUrl(metadata.opencodeServerBaseUrl, metadata.opencodeServerBaseUrlExplicit),
        serverBaseUrlExplicit: runtimeDescriptor?.serverBaseUrlExplicit ?? normalizeOpenCodeServerBaseUrlExplicit(metadata.opencodeServerBaseUrlExplicit),
    };
}
export function readOpenCodeSessionRuntimeHandleFromMetadata(metadata) {
    if (!isRecord(metadata)) {
        return {
            backendMode: null,
            serverBaseUrl: null,
            serverBaseUrlExplicit: false,
            vendorSessionId: null,
        };
    }
    const runtimeDescriptor = readSessionMetadataRuntimeDescriptor(metadata, 'opencode');
    return {
        ...readOpenCodeSessionAffinityFromMetadata(metadata),
        vendorSessionId: runtimeDescriptor?.vendorSessionId ?? readLegacyOpenCodeVendorSessionId(metadata),
    };
}
//# sourceMappingURL=opencodeSessionRuntimeHandle.js.map