export interface TimmyState {
  mood: string;
  activity: string;
}

export interface WorldState {
  timmyState: TimmyState;
  agentStates: Record<string, string>;
  updatedAt: string;
}

const DEFAULT_TIMMY: TimmyState = {
  mood: "contemplative",
  activity: "idle",
};

const _state: WorldState = {
  timmyState: { ...DEFAULT_TIMMY },
  agentStates: { alpha: "idle", beta: "idle", gamma: "idle", delta: "idle" },
  updatedAt: new Date().toISOString(),
};

export function getWorldState(): WorldState {
  return {
    timmyState: { ..._state.timmyState },
    agentStates: { ..._state.agentStates },
    updatedAt: _state.updatedAt,
  };
}

export function setAgentStateInWorld(agentId: string, agentState: string): void {
  _state.agentStates[agentId] = agentState;
  _state.updatedAt = new Date().toISOString();
  _deriveTimmy();
}

function _deriveTimmy(): void {
  const states = Object.values(_state.agentStates);
  if (states.includes("working")) {
    _state.timmyState.activity = "working";
    _state.timmyState.mood = "focused";
  } else if (states.includes("thinking") || states.includes("evaluating")) {
    _state.timmyState.activity = "thinking";
    _state.timmyState.mood = "curious";
  } else if (states.some((s) => s !== "idle")) {
    _state.timmyState.activity = "active";
    _state.timmyState.mood = "attentive";
  } else {
    _state.timmyState.activity = "idle";
    _state.timmyState.mood = "contemplative";
  }
}
