// This program has been developed by students from the bachelor Computer Science at Utrecht
// University within the Software Project course.
// © Copyright Utrecht University (Department of Information and Computing Sciences)
import useProgramStore from "../../utils/programStore";
import orderPhaseNodeArray from "../../utils/orderPhaseNodes";
import useFlowStore from './visualProgrammingUI/VisProgStores';
import { NodeReduces } from './visualProgrammingUI/NodeRegistry';
import type { PhaseNode } from "./visualProgrammingUI/nodes/PhaseNode";
import { API_BASE_URL } from "../../config/api.ts";

/**
 * Reduces the graph into its phases' information and recursively calls their reducing function
 */ 
export function graphReducer() {
  const { nodes } = useFlowStore.getState();
  return orderPhaseNodeArray(nodes.filter((n) => n.type == 'phase') as PhaseNode [])
    .map((n) => {
      const reducer = NodeReduces['phase'];
      return reducer(n, nodes)
    }); 
}


/**
 * Outputs the prepared program to the console and sends it to the backend
 */
export function runProgram() {
  const phases = graphReducer();
  const program = {phases}
  console.log(JSON.stringify(program, null, 2));
  fetch(
    `${API_BASE_URL}/program`,
    {
      method: "POST",
      headers: {"Content-Type": "application/json"},
      body: JSON.stringify(program),
    }
  ).then((res) => {
    if (!res.ok) throw new Error("Failed communicating with the backend.")
    console.log("Successfully sent the program to the backend.");

    // store reduced program in global program store for further use in the UI
    // when the program was sent to the backend successfully:
    useProgramStore.getState().setProgramState(structuredClone(program));
  }).catch(() => console.log("Failed to send program to the backend."));
  console.log(program);
}
