const domains = {
  honestyHumility: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  emotionality: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
  extraversion: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
  agreeableness: [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
  conscientiousness: [41, 42, 43, 44, 45, 46, 47, 48, 49, 50],
  openness: [51, 52, 53, 54, 55, 56, 57, 58, 59, 60],
} as const;

const reverseItems = new Set([
  2, 4, 6, 8, 10,
  12, 14, 16, 18, 20,
  22, 24, 26, 28, 30,
  32, 34, 36, 38, 40,
  42, 44, 46, 48, 50,
  52, 54, 56, 58, 60,
]);

function scoreItem(answers: string[], item: number) {
  const raw = Number(answers[item - 1] || 1);
  return reverseItems.has(item) ? 6 - raw : raw;
}

function average(scores: number[]) {
  return scores.reduce((sum, score) => sum + score, 0) / scores.length;
}

function domainAverage(answers: string[], items: readonly number[]) {
  return average(items.map((item) => scoreItem(answers, item)));
}

export function calculateHEXACOResults(answers: string[]) {
  return {
    honestyHumility: domainAverage(answers, domains.honestyHumility),
    emotionality: domainAverage(answers, domains.emotionality),
    extraversion: domainAverage(answers, domains.extraversion),
    agreeableness: domainAverage(answers, domains.agreeableness),
    conscientiousness: domainAverage(answers, domains.conscientiousness),
    openness: domainAverage(answers, domains.openness),
  };
}
