import type { EventDefinition, EventPlayerContext } from '../types.js';

function numberOrZero(value: unknown): number {
  return typeof value === 'number' ? value : 0;
}

function hasOccupation(player: EventPlayerContext, occupation: string): boolean {
  return (player.c.occupation as string | undefined) === occupation;
}

function choice(
  choiceId: string,
  text: string,
  resolutionText: string,
  overrides?: Partial<EventDefinition['choices'][number]>
): EventDefinition['choices'][number] {
  return {
    choiceId,
    text,
    resolutionText,
    ...overrides,
  };
}

export const dilemmaCatalog: EventDefinition[] = [
  {
    id: 'bullyDilemma',
    category: 'dilemmas',
    prompt: 'Your friend is being bullied at school. What do you do?',
    minAge: 10,
    maxAge: 17,
    choices: [
      choice(
        'stand_up_for_friend',
        'Stand up for your friend',
        'You stepped in and the bullies backed off. Your friend trusts you more.',
        { energyCost: 5, effects: { stats: { happiness: 10, social: 5 } } }
      ),
      choice(
        'do_nothing',
        "Don't do anything",
        'You stayed out of it and your friend felt abandoned.',
        { effects: { stats: { happiness: -10, social: -5 } } }
      ),
      choice(
        'join_bullying',
        'Join in on the bullying',
        'You joined the bullies. The social fallout hurt your reputation.',
        { energyCost: 5, effects: { stats: { happiness: -20, social: -20 } } }
      ),
    ],
  },
  {
    id: 'braceletDilemma',
    category: 'dilemmas',
    prompt: 'A classmate is wearing your missing bracelet. How do you respond?',
    minAge: 5,
    maxAge: 17,
    choices: [
      choice(
        'confront_directly',
        'Confront them directly',
        'You confronted them, got the bracelet back, and felt relieved.',
        { energyCost: 5, effects: { stats: { happiness: 10 } } }
      ),
      choice(
        'tell_teacher',
        'Tell the teacher',
        'A teacher handled it and returned the bracelet.',
        { energyCost: 3, effects: { stats: { happiness: 5 } } }
      ),
      choice(
        'let_it_go',
        "Don't do anything",
        'You let it go and felt worse every time you saw it.',
        { effects: { stats: { happiness: -10 } } }
      ),
    ],
  },
  {
    id: 'foundLostPet',
    category: 'dilemmas',
    prompt: 'You found a lost dog with a collar but no owner nearby. What do you do?',
    minAge: 8,
    choices: [
      choice(
        'vet_chip_scan',
        'Take it to a vet to scan the chip',
        'The vet found the owner and the reunion was emotional.',
        { energyCost: 15, effects: { stats: { happiness: 20, social: 15 } } }
      ),
      choice(
        'post_social',
        'Post on social media',
        'Your post found the owner quickly and you helped reunite them.',
        { effects: { stats: { happiness: 10, social: 10 } } }
      ),
      choice(
        'keep_pet',
        'Keep the dog',
        'You kept the dog, but guilt lingered about the missing owner.',
        { effects: { stats: { happiness: 10, social: -20 } } }
      ),
      choice(
        'walk_away',
        'Leave it and walk away',
        'You walked away and wondered if you should have helped.',
        { effects: { stats: { happiness: -10 } } }
      ),
    ],
  },
  {
    id: 'friendCheating',
    category: 'dilemmas',
    prompt: 'You discover a close friend is cheating on their partner. What do you do?',
    minAge: 16,
    choices: [
      choice(
        'tell_partner',
        'Tell the partner',
        'You told the partner. It was honest, but your friendship took major damage.',
        { energyCost: 10, effects: { stats: { social: -10 } } }
      ),
      choice(
        'confront_friend',
        'Confront your friend',
        'You confronted your friend and forced a difficult but honest conversation.',
        { energyCost: 15, effects: { stats: { social: -5 } } }
      ),
      choice(
        'stay_out',
        'Stay out of it',
        'You stayed out and carried quiet guilt.',
        { effects: { stats: { happiness: -10 } } }
      ),
      choice(
        'support_anyway',
        'Support your friend regardless',
        'You stayed loyal, but felt uneasy supporting the behavior.',
        { effects: { stats: { happiness: -15, social: 5 } } }
      ),
    ],
  },
  {
    id: 'foundExpensiveItem',
    category: 'dilemmas',
    prompt: 'You find an expensive phone in a store. What do you do?',
    minAge: 10,
    choices: [
      choice(
        'turn_in',
        'Turn it in to the store',
        'You turned it in and later received a thank-you reward.',
        { effects: { stats: { happiness: 15, social: 20 }, resources: { money: 50, diamonds: 10 } } }
      ),
      choice(
        'find_owner',
        'Look for the owner yourself',
        'You tracked down the owner and returned it personally.',
        { energyCost: 20, effects: { stats: { happiness: 25 } } }
      ),
      choice(
        'keep_it',
        'Keep it',
        'You kept the phone. The gain came with guilt.',
        { effects: { stats: { happiness: -30 }, resources: { money: 200 } } }
      ),
      choice(
        'leave_it',
        'Leave it where it is',
        'You left it and hoped the owner would recover it.',
        { effects: { stats: { happiness: -5 } } }
      ),
    ],
  },
  {
    id: 'colleagueStealingCredit',
    category: 'dilemmas',
    prompt: 'A coworker took credit for your work in a meeting. What now?',
    minAge: 22,
    maxAge: 65,
    isEligible: (player) => hasOccupation(player, 'work'),
    choices: [
      choice(
        'public_callout',
        'Call them out publicly',
        'You called them out publicly and became right but polarizing.',
        { effects: { stats: { happiness: 10, social: -20 } } }
      ),
      choice(
        'private_talk',
        'Talk to them privately',
        'A private conversation helped repair the issue quietly.',
        { energyCost: 10, effects: { stats: { happiness: 10, social: 5 } } }
      ),
      choice(
        'tell_boss',
        'Tell your boss',
        'Your boss corrected the record, but workplace trust dipped.',
        { effects: { stats: { happiness: 15, social: -10 } } }
      ),
      choice(
        'let_it_go',
        'Let it go',
        'You let it go and felt resentment build over time.',
        { effects: { stats: { happiness: -20, social: -5 } } }
      ),
    ],
  },
  {
    id: 'strayAnimalDecision',
    category: 'dilemmas',
    prompt: "There's a stray animal in your neighborhood that needs help. What do you do?",
    minAge: 10,
    choices: [
      choice(
        'adopt',
        'Adopt it',
        'You adopted the animal and gained a loyal companion.',
        { energyCost: 15, moneyCost: 200, effects: { stats: { happiness: 30 } } }
      ),
      choice(
        'shelter',
        'Take it to a shelter',
        'You took it to a shelter where it could be cared for.',
        { energyCost: 10, effects: { stats: { happiness: 15 } } }
      ),
      choice(
        'feed_and_leave',
        'Feed it but leave it',
        'You helped in the short term, but the problem stayed unresolved.',
        { moneyCost: 50, effects: { stats: { happiness: 10 } } }
      ),
      choice(
        'do_nothing',
        'Do nothing',
        'You did nothing and felt guilty about it.',
        { effects: { stats: { happiness: -10 } } }
      ),
    ],
  },
  {
    id: 'witnessShoplifting',
    category: 'dilemmas',
    prompt: 'You witness someone shoplifting food. How do you respond?',
    minAge: 12,
    choices: [
      choice(
        'tell_staff',
        'Tell store staff',
        'You reported it and followed policy, but felt conflicted.',
        { effects: { stats: { social: -10, happiness: -5 } } }
      ),
      choice(
        'buy_food',
        'Offer to buy food',
        'You bought food and helped someone in immediate need.',
        { moneyCost: 25, effects: { stats: { happiness: 25, social: 10 } } }
      ),
      choice(
        'look_away',
        'Look the other way',
        "You looked away and chose not to intervene.",
        { effects: { stats: { happiness: -5 } } }
      ),
      choice(
        'talk_to_them',
        'Talk to them about it',
        'A direct conversation led to support resources instead of punishment.',
        { energyCost: 10, effects: { stats: { happiness: 15, social: 10 } } }
      ),
    ],
  },
  {
    id: 'friendBorrowMoney',
    category: 'dilemmas',
    prompt: 'A close friend asks to borrow money during a crisis. Do you lend it?',
    minAge: 18,
    isEligible: (player) => numberOrZero(player.c.money) >= 500,
    choices: [
      choice(
        'lend_full',
        'Lend the full amount',
        'You lent the full amount and accepted the risk to the friendship.',
        { moneyCost: 500, effects: { stats: { social: 10 } } }
      ),
      choice(
        'lend_with_contract',
        'Lend with a contract',
        'You protected both sides with clear expectations and repayment terms.',
        { moneyCost: 505, effects: { stats: { social: 5 } } }
      ),
      choice(
        'lend_partial',
        'Offer a smaller amount',
        'You offered partial help and reduced your financial risk.',
        { moneyCost: 100, effects: { stats: { happiness: -5 } } }
      ),
      choice(
        'decline',
        'Decline to lend',
        'You declined and the friendship became tense for a while.',
        { effects: { stats: { happiness: -10, social: -15 } } }
      ),
    ],
  },
  {
    id: 'environmentalChoice',
    category: 'dilemmas',
    prompt: 'You need to travel long-distance. Do you prioritize cost, convenience, or impact?',
    minAge: 16,
    choices: [
      choice(
        'cheap_flight',
        'Take the cheap flight',
        'You saved money but felt drained and conflicted about impact.',
        { energyCost: 30, moneyCost: 200, effects: { stats: { happiness: -5 } } }
      ),
      choice(
        'eco_option',
        'Pay for the eco-friendlier option',
        'You paid more and felt better aligned with your values.',
        { moneyCost: 400, effects: { stats: { happiness: 15 } } }
      ),
      choice(
        'skip_trip',
        "Don't make the trip",
        'You skipped the trip and accepted missing out.',
        { effects: { stats: { happiness: -10, social: -10 } } }
      ),
      choice(
        'train_bus',
        'Take train or bus',
        'You took a slower route and felt good about the lower impact.',
        { energyCost: 40, moneyCost: 150, effects: { stats: { happiness: 10 } } }
      ),
    ],
  },
  {
    id: 'parentCareDecision',
    category: 'dilemmas',
    prompt: 'A parent can no longer live independently. What care plan do you choose?',
    minAge: 40,
    maxAge: 70,
    choices: [
      choice(
        'nursing_home',
        'Move them to a nursing home',
        'They received professional care, but you carried emotional guilt.',
        { moneyCost: 3000, effects: { stats: { happiness: -20 } } }
      ),
      choice(
        'live_with_you',
        'Have them live with you',
        'Caregiving was demanding, but meaningful and close.',
        { energyCost: 30, moneyCost: 500, effects: { stats: { happiness: 10 } } }
      ),
      choice(
        'in_home_care',
        'Hire in-home care',
        'You balanced safety, dignity, and independence at high cost.',
        { moneyCost: 2000, effects: { stats: { happiness: 5 } } }
      ),
      choice(
        'siblings_support',
        'Rely on siblings for shared care',
        'Coordination conflicts strained family relationships.',
        { effects: { stats: { happiness: -15, social: -15 } } }
      ),
    ],
  },
  {
    id: 'whistleblowerDecision',
    category: 'dilemmas',
    prompt: 'You discover unethical behavior at work. What do you do?',
    minAge: 25,
    maxAge: 65,
    isEligible: (player) => hasOccupation(player, 'work'),
    choices: [
      choice(
        'report_authorities',
        'Report to authorities',
        'You reported externally and accepted personal career risk for accountability.',
        { moneyCost: 20, effects: { stats: { happiness: 20 } } }
      ),
      choice(
        'report_internal',
        'Report internally',
        'You used internal channels and stayed employed under scrutiny.',
        { effects: { stats: { happiness: 10, social: -10 } } }
      ),
      choice(
        'job_first',
        'Find a new job first',
        'You prioritized stability and exited before escalating.',
        { energyCost: 30, effects: { stats: { happiness: -10 } } }
      ),
      choice(
        'stay_silent',
        'Stay silent',
        'You stayed silent for security, but the guilt was heavy.',
        { effects: { stats: { happiness: -30 } } }
      ),
    ],
  },
  {
    id: 'plagiarismAccusation',
    category: 'dilemmas',
    prompt: "You're accused of plagiarism on a major assignment. How do you respond?",
    minAge: 14,
    maxAge: 22,
    isEligible: (player) => hasOccupation(player, 'student'),
    choices: [
      choice(
        'prove_original',
        'Prove the work is yours',
        'You documented your process and cleared your name.',
        { energyCost: 30, effects: { stats: { happiness: 15, social: 10 } } }
      ),
      choice(
        'accept_partial',
        'Accept partial blame',
        'The issue closed quickly, but your record and confidence took a hit.',
        { effects: { stats: { happiness: -20, social: -5 } } }
      ),
      choice(
        'fight_aggressively',
        'Fight the accusation aggressively',
        'You fought hard and won, but damaged trust with faculty.',
        { energyCost: 40, effects: { stats: { happiness: 5, social: -25 } } }
      ),
      choice(
        'request_meeting',
        'Request a calm meeting',
        'A direct meeting resolved the misunderstanding constructively.',
        { energyCost: 15, effects: { stats: { happiness: 20, social: 15 } } }
      ),
    ],
  },
  {
    id: 'legalTrouble',
    category: 'dilemmas',
    prompt: "You're facing legal trouble with serious consequences. What's your approach?",
    minAge: 16,
    // PACING (T011b): generic adult/working-age beat. Was maxAge 100 and stayed
    // eligible into the 80s/90s, crowding out late-life content. Narrowed to 70
    // so the third act is owned by lateLife events.
    maxAge: 70,
    choices: [
      choice(
        'hire_lawyer',
        'Hire an expensive lawyer',
        'You paid heavily for strong representation and reduced legal risk.',
        { moneyCost: 5000, effects: { stats: { happiness: 10 } } }
      ),
      choice(
        'public_defender',
        'Use a public defender',
        'You accepted limited resources and an uncertain legal outcome.',
        { effects: { stats: { happiness: -15 } } }
      ),
      choice(
        'self_represent',
        'Represent yourself',
        'You represented yourself under extreme pressure and high risk.',
        { energyCost: 50, effects: { stats: { happiness: -20, social: -10 } } }
      ),
      choice(
        'settle',
        'Settle out of court',
        'You settled to close the case quickly at a major financial cost.',
        { moneyCost: 2000, effects: { stats: { happiness: 5 } } }
      ),
    ],
  },
];

export function resolveDilemmaChoice(eventId: string, choiceId: string): string | null {
  const definition = dilemmaCatalog.find((event) => event.id === eventId);
  if (!definition) {
    return null;
  }

  const selectedChoice = definition.choices.find((choiceItem) => choiceItem.choiceId === choiceId);
  return selectedChoice?.resolutionText ?? null;
}
