const PROVENANCE_PRIORITY = {
    declared: 4,
    observed: 3,
    inferred: 2,
    unknown: 1,
};
function normalizedValue(value) {
    return typeof value === 'string' && value.trim().length > 0
        ? value.trim()
        : 'unknown';
}
function normalizeRecord(record) {
    return {
        ...record,
        value: normalizedValue(record.value),
    };
}
function strongestRecord(records, provenance) {
    return records.find((record) => record.provenance === provenance && record.value !== 'unknown');
}
function strongestKnownRecord(records) {
    return records
        .filter((record) => record.value !== 'unknown')
        .sort((left, right) => PROVENANCE_PRIORITY[right.provenance] -
        PROVENANCE_PRIORITY[left.provenance])[0];
}
function resolved(record, confidence, mismatch, records) {
    const value = record.value;
    return {
        value,
        provenance: record.provenance,
        confidence,
        mismatch,
        diversityClaimable: value !== 'unknown' &&
            record.provenance !== 'unknown' &&
            confidence !== 'unknown',
        records,
    };
}
export function resolveIdentityConfidence(records) {
    const normalizedRecords = records.map(normalizeRecord);
    const declared = strongestRecord(normalizedRecords, 'declared');
    const observed = strongestRecord(normalizedRecords, 'observed');
    if (declared && observed) {
        if (declared.value === observed.value) {
            return resolved(declared, 'high', false, normalizedRecords);
        }
        return resolved(observed, 'low', true, normalizedRecords);
    }
    if (declared) {
        return resolved(declared, declared.rejectOnInvalid === true ? 'high' : 'medium', false, normalizedRecords);
    }
    if (observed) {
        return resolved(observed, 'low', false, normalizedRecords);
    }
    const inferred = strongestRecord(normalizedRecords, 'inferred');
    if (inferred) {
        return resolved(inferred, 'low', false, normalizedRecords);
    }
    const fallback = strongestKnownRecord(normalizedRecords) ?? {
        value: 'unknown',
        provenance: 'unknown',
    };
    return resolved(fallback, 'unknown', false, normalizedRecords);
}
