import { eventBus } from '../lib/eventBus.js';
import { saveState } from './SaveState.js';

class BehaviorTracker {
  constructor() {
    this._curiosity = 50;
    this._obedience = 50;
    this._risk = 50;
    this._suspicion = 0;
  }

  initialize(state) {
    const b = state?.behavior ?? {};
    this._curiosity  = typeof b.curiosity  === 'number' ? b.curiosity  : 50;
    this._obedience  = typeof b.obedience  === 'number' ? b.obedience  : 50;
    this._risk       = typeof b.risk       === 'number' ? b.risk       : 50;
    this._suspicion  = typeof b.suspicion  === 'number' ? b.suspicion  :  0;
  }

  apply(impact) {
    if (!impact || typeof impact !== 'object') return;
    const clamp = (v) => Math.max(0, Math.min(100, v));
    if (typeof impact.curiosity_delta  === 'number') this._curiosity  = clamp(this._curiosity  + impact.curiosity_delta);
    if (typeof impact.obedience_delta  === 'number') this._obedience  = clamp(this._obedience  + impact.obedience_delta);
    if (typeof impact.risk_delta       === 'number') this._risk       = clamp(this._risk       + impact.risk_delta);
    if (typeof impact.suspicion_delta  === 'number') this._suspicion  = clamp(this._suspicion  + impact.suspicion_delta);
    this._persist();
    eventBus.emit('behavior:changed', this.getSnapshot());
  }

  getSnapshot() {
    return {
      curiosity:  this._curiosity,
      obedience:  this._obedience,
      risk:       this._risk,
      suspicion:  this._suspicion
    };
  }

  setSnapshot(override) {
    const clamp = (v) => Math.max(0, Math.min(100, v));
    if (typeof override.curiosity  === 'number') this._curiosity  = clamp(override.curiosity);
    if (typeof override.obedience  === 'number') this._obedience  = clamp(override.obedience);
    if (typeof override.risk       === 'number') this._risk       = clamp(override.risk);
    if (typeof override.suspicion  === 'number') this._suspicion  = clamp(override.suspicion);
    this._persist();
  }

  _persist() {
    saveState.set({ behavior: this.getSnapshot() });
  }
}

export const behaviorTracker = new BehaviorTracker();
