import { buildBackendTargetKey } from '@happier-dev/protocol';
import { AGENTS_CORE } from '../manifest.js';
import { isCodexVendorResumeBackendEnabled } from '../providerSettings/definitions/codex.js';
import { resolvePersistedCodexRuntimeIdentity } from './codexRuntimeIdentity.js';
import { resolveVendorResumeIdFromSessionMetadata } from './vendorResumePolicy.js';
function asRecord(value) {
    if (!value || typeof value !== 'object' || Array.isArray(value))
        return null;
    return value;
}
function isBackendDisabledByAccountSettings(agentId, accountSettings) {
    const backendEnabledByTargetKey = accountSettings?.backendEnabledByTargetKey;
    const backendEnabledByTargetKeyRecord = asRecord(backendEnabledByTargetKey);
    if (!backendEnabledByTargetKeyRecord)
        return false;
    return backendEnabledByTargetKeyRecord[buildBackendTargetKey({ kind: 'builtInAgent', agentId })] === false;
}
function isCodexVendorHandoffEnabled(input) {
    const runtimeIdentity = resolvePersistedCodexRuntimeIdentity(input.metadata);
    if (runtimeIdentity?.backendMode === 'acp' || runtimeIdentity?.backendMode === 'appServer') {
        return true;
    }
    return isCodexVendorResumeBackendEnabled(input.accountSettings ?? {});
}
export function resolveVendorHandoffIdFromSessionMetadata(agentId, metadata) {
    return resolveVendorResumeIdFromSessionMetadata(agentId, metadata);
}
export function evaluateVendorHandoffEligibility(input) {
    const accountSettings = asRecord(input.accountSettings) ?? null;
    if (isBackendDisabledByAccountSettings(input.agentId, accountSettings)) {
        return { eligible: false, reasonCode: 'backend_disabled_by_account_settings' };
    }
    const agent = AGENTS_CORE[input.agentId];
    if (!agent.sessionStorage[input.storageMode]) {
        return { eligible: false, reasonCode: 'storage_mode_unsupported' };
    }
    if (agent.handoff.vendorStateTransfer === 'unsupported') {
        return { eligible: false, reasonCode: 'handoff_unsupported' };
    }
    if (agent.handoff.vendorStateTransfer === 'experimental') {
        if (input.agentId === 'codex') {
            if (!isCodexVendorHandoffEnabled({ metadata: input.metadata, accountSettings })) {
                return { eligible: false, reasonCode: 'experimental_disabled' };
            }
        }
        else {
            return { eligible: false, reasonCode: 'experimental_disabled' };
        }
    }
    const vendorHandoffId = resolveVendorHandoffIdFromSessionMetadata(input.agentId, input.metadata);
    if (!vendorHandoffId) {
        return { eligible: false, reasonCode: 'vendor_handoff_id_missing' };
    }
    return { eligible: true, vendorHandoffId };
}
//# sourceMappingURL=vendorHandoffPolicy.js.map