import { eventBus } from '../lib/eventBus.js';
import { saveState } from './SaveState.js';
import { behaviorTracker } from './BehaviorTracker.js';
import { hiddenHookTracker } from './HiddenHookTracker.js';
import { narrativePhaseTracker } from './NarrativePhaseTracker.js';

const PHASE_RANK = {
  normal_work: 0, unease: 1, suspicion: 2,
  investigation: 3, conflict: 4, resolution: 5
};

class EndingEvaluator {
  evaluate() {
    const state = saveState.get() ?? {};
    const trust = Number(state.trust ?? 50);
    const { curiosity, obedience, risk } = behaviorTracker.getSnapshot();
    const hooksDiscovered = hiddenHookTracker.getDiscovered().length;
    const phaseRank = PHASE_RANK[narrativePhaseTracker.getPhase()] ?? 0;

    const candidates = [];

    // exposure: investigative player who found hidden hooks
    if (curiosity >= 65 && hooksDiscovered >= 2 && phaseRank >= PHASE_RANK.investigation) {
      candidates.push('exposure');
    }
    // chaos: high risk, low trust
    if (risk >= 65 && trust <= 40) {
      candidates.push('chaos');
    }
    // corporate_loop: compliant, trusted, incurious
    if (obedience >= 65 && curiosity <= 40 && trust >= 65) {
      candidates.push('corporate_loop');
    }
    // burnout: passive disengagement
    if (curiosity <= 35 && obedience <= 40) {
      candidates.push('burnout');
    }

    // Priority: exposure > chaos > corporate_loop > burnout
    const priority = ['exposure', 'chaos', 'corporate_loop', 'burnout'];
    const active = priority.find((e) => candidates.includes(e)) ?? 'undetermined';

    return { active, candidates };
  }

  checkTrigger() {
    const result = this.evaluate();
    if (narrativePhaseTracker.getPhase() === 'resolution' && result.active !== 'undetermined') {
      eventBus.emit('ending:triggered', { ending: result.active });
    }
    return result;
  }
}

export const endingEvaluator = new EndingEvaluator();
