/**
 * Full Lifecycle Analysis Script
 * Runs a complete life simulation and identifies issues
 */

import { HeadlessGame } from '../src/testing/index.js';

async function runTest() {
  console.log('=== Running Full Lifecycle Test ===\n');

  const game = new HeadlessGame({
    autoRespond: true,
    responseStrategy: 'random',
    logResponses: true,
  });

  // Run to death or max age
  await game.advanceToEnd(120);

  // Print summary
  game.printSummary();

  // Check milestones
  const milestones = [
    'learnedWalk', 'learningColors', 'lostFirstTooth', 'lostLastTooth',
    'learningToDrive', 'firstJob', 'jobOffer'
  ];
  console.log('=== Milestone Events ===');
  for (const m of milestones) {
    console.log(`  ${m}: ${game.hasEvent(m) ? 'YES' : 'NO'}`);
  }

  // Check key stats
  console.log('\n=== Final Stats ===');
  console.log(`  Money: $${game.player.c.money?.toFixed(0) ?? 0}`);
  console.log(`  Occupation: ${game.player.c.occupation ?? 'none'}`);
  console.log(`  Job: ${game.player.c.job?.title ?? 'none'}`);
  console.log(`  Salary: $${game.player.c.salary ?? 0}`);
  console.log(`  Happiness: ${game.player.c.happiness ?? 0}`);
  console.log(`  Health: ${game.player.c.health ?? 0}`);

  // Romance information
  console.log('\n=== Romance Status ===');
  const summary = game.getSummary();
  console.log(`  Has Partner: ${summary.hasPartner}`);
  console.log(`  Relationship Status: ${summary.relationshipStatus ?? 'none'}`);
  console.log(`  Romance Events: ${summary.romanceEventsCount}`);
  const romanceLog = game.getRomanceLog();
  if (romanceLog.length > 0) {
    console.log('  Romance Timeline:');
    for (const entry of romanceLog) {
      console.log(`    Age ${entry.age}: ${entry.event} ${entry.partnerName ? `(${entry.partnerName})` : ''}`);
    }
  }
  console.log(`  Children: ${(game.player.c as unknown as { children?: { length: number } }).children?.length ?? 0}`);

  // Event categories
  const events = game.getEvents();
  const questions = game.getQuestions();

  console.log('\n=== Event Breakdown ===');
  console.log(`  Total events: ${events.length}`);
  console.log(`  Total questions: ${questions.length}`);
  console.log(`  Questions answered: ${game.getResponseLog().length}`);

  // Count event types
  const eventTypes: Record<string, number> = {};
  for (const e of events) {
    const id = e.event.id.replace(/_\d+$/, '');
    eventTypes[id] = (eventTypes[id] || 0) + 1;
  }

  console.log('\n=== Top 15 Event Types ===');
  const sorted = Object.entries(eventTypes).sort((a, b) => b[1] - a[1]).slice(0, 15);
  for (const [name, count] of sorted) {
    console.log(`  ${name}: ${count}`);
  }

  // Check for any issues
  console.log('\n=== Potential Issues ===');
  const issues: string[] = [];

  if (!game.hasEvent('learnedWalk')) issues.push('Never learned to walk');
  if (!game.hasEvent('lostFirstTooth')) issues.push('Never lost first tooth');
  if (!game.hasEvent('learningToDrive') && game.player.c.ageYears >= 17) issues.push('Never learned to drive');
  if ((game.player.c.money ?? 0) < 100 && game.player.c.ageYears > 30) issues.push('Very low lifetime earnings');
  if (!game.player.c.job && game.player.c.ageYears > 25 && game.player.c.ageYears < 65) issues.push('Never had a job');
  if ((game.player.c.happiness ?? 50) < 20) issues.push('Very low happiness');
  if (questions.length < 10) issues.push('Very few questions asked');
  if (!summary.hasPartner && game.player.c.ageYears > 40) issues.push('Never found a partner');
  if (summary.romanceEventsCount === 0 && game.player.c.ageYears > 25) issues.push('No romance events occurred');

  if (issues.length === 0) {
    console.log('  None detected!');
  } else {
    for (const issue of issues) {
      console.log(`  ⚠️  ${issue}`);
    }
  }

  // Sample of unique events
  console.log('\n=== Unique Events (sample) ===');
  const uniqueEvents = [...new Set(events.map(e => e.event.id.replace(/_\d+$/, '')))];
  console.log(`  Total unique: ${uniqueEvents.length}`);
  console.log(`  Sample: ${uniqueEvents.slice(0, 25).join(', ')}`);

  // Check player tracked events vs output events
  console.log('\n=== Player Internal Event Tracking ===');
  console.log(`  player.events Set size: ${game.player.events.size}`);
  console.log(`  player.askedQuestions Set size: ${game.player.askedQuestions.size}`);

  // List some internal events
  const internalEvents = Array.from(game.player.events).slice(0, 20);
  console.log(`  Sample events: ${internalEvents.join(', ')}`);
}

runTest().catch(console.error);
