import type { UpdateStateMessage } from "@codeflash/types";
import type { State } from "../root";

const LEGACY_STATUS: UpdateStateMessage["payload"]["status"][] = [
  "connecting",
  "idle",
  "noPythonFile",
  "success",
  "error",
  "serverError",
  "empty",
];

export const handleUpdateState = (
  oldState: State,
  message: UpdateStateMessage,
): State => {
  const payload = message.payload;

  // console.log(
  //   `received update state message: ${message.type}, ${JSON.stringify(payload)}`,
  // );

  const update: Partial<State> = {};

  if (payload.currentFilePath) {
    update["currentFilePath"] = payload.currentFilePath;
  }
  if (payload.status && !LEGACY_STATUS.includes(payload.status)) {
    update["status"] = payload.status;
  }
  if (payload.functionData) {
    update["functionsInCurrentFile"] = payload.functionData;
  }

  // const msg = payload.message;
  return {
    ...oldState,
    ...update,
  };
};
