/** §9 endings — priority E4 → E3 → E2 → E1 */

export type EndingId = 'E1' | 'E2' | 'E3' | 'E4';

export interface EndingEvalInput {
  awareness: number;
  happiness: number;
  clueCount: number;
  /** Day 5–7 happiness continuously ≤10 */
  lowHappinessStreakD5to7: boolean;
  /** Escapes from forced celebration */
  celebrationEscapes: number;
  /** Player walked to fog wall during T15 */
  choseFogWall: boolean;
}

export interface EndingResult {
  id: EndingId;
  name: string;
}

/**
 * Priority (first match wins):
 * E4: Day5–7 happiness ≤10 continuously AND celebration escapes ×3
 * E3: awareness ≥70 AND clues ≥6/9 AND chose fog wall
 * E2: awareness 30–69
 * E1: awareness ≤29 AND happiness ≥90
 * Fallback: E2 if mid awareness without fog; E1-like sugar if high happiness; else E2
 */
export function evaluateEnding(input: EndingEvalInput): EndingId {
  if (input.lowHappinessStreakD5to7 && input.celebrationEscapes >= 3) {
    return 'E4';
  }
  if (input.awareness >= 70 && input.clueCount >= 6 && input.choseFogWall) {
    return 'E3';
  }
  if (input.awareness >= 30 && input.awareness <= 69) {
    return 'E2';
  }
  if (input.awareness <= 29 && input.happiness >= 90) {
    return 'E1';
  }
  // If E3 conditions almost met but no fog wall, or other edge: prefer E2 when awareness mid-high
  if (input.awareness >= 70 && input.clueCount >= 6 && !input.choseFogWall) {
    return 'E2';
  }
  if (input.happiness >= 90) {
    return 'E1';
  }
  return 'E2';
}

export const ENDING_SUBTITLES: Record<EndingId, string[]> = {
  E4: ['系统检测到疗程无效。'],
  E3: [], // special: medical record + real face
  E2: ['疗程重新开始。'],
  E1: ['从此，每一天都很幸福。', '每一天。'],
};

export const ENDING_NAMES: Record<EndingId, string> = {
  E4: '静默',
  E3: '苏醒',
  E2: '回收',
  E1: '糖衣',
};
