import { Dimension, Direction, IPsychometricStatementDocument } from '../models/psychometricStatement';
import { DimensionScore, PersonalityProfile } from '../models/psychometricResult';

interface ResponseInput {
  statement: string; // statement ID
  value: number;     // 1-5 (strongly disagree → strongly agree)
}

const DIMENSION_LABELS: Record<Dimension, [string, string]> = {
  EI: ['E', 'I'],
  SN: ['S', 'N'],
  TF: ['T', 'F'],
  JP: ['J', 'P'],
};

/**
 * Calculate personality profile from responses.
 *
 * For each statement:
 * - "positive" direction: agreement (high value) scores toward the FIRST trait (E, S, T, J)
 * - "negative" direction: agreement (high value) scores toward the SECOND trait (I, N, F, P)
 *
 * Scale: 1-5, so max per statement = 5
 * Percentage = (sum for trait / max possible) * 100
 */
export const calculateProfile = (
  responses: ResponseInput[],
  statementMap: Map<string, IPsychometricStatementDocument>,
): { profile: PersonalityProfile; personality_type: string } => {
  const scores: Record<Dimension, { first: number; second: number; count: number }> = {
    EI: { first: 0, second: 0, count: 0 },
    SN: { first: 0, second: 0, count: 0 },
    TF: { first: 0, second: 0, count: 0 },
    JP: { first: 0, second: 0, count: 0 },
  };

  for (const { statement, value } of responses) {
    const stmt = statementMap.get(statement);
    if (!stmt) continue;

    const dim = stmt.dimension;
    scores[dim].count++;

    if (stmt.direction === 'positive') {
      scores[dim].first += value;
      scores[dim].second += 6 - value;
    } else {
      scores[dim].second += value;
      scores[dim].first += 6 - value;
    }
  }

  const profile = {} as PersonalityProfile;
  let personality_type = '';

  for (const dim of ['EI', 'SN', 'TF', 'JP'] as Dimension[]) {
    const { first, second, count } = scores[dim];
    const total = first + second;

    const dimScore: DimensionScore = total > 0
      ? { first: Math.round((first / total) * 100), second: Math.round((second / total) * 100) }
      : { first: 50, second: 50 };

    profile[dim] = dimScore;

    const [firstLabel, secondLabel] = DIMENSION_LABELS[dim];
    personality_type += dimScore.first >= dimScore.second ? firstLabel : secondLabel;
  }

  return { profile, personality_type };
};
