export function createMachineSessionReadonlyStatus({
  stateBundle = null,
  workflowStatus = null,
  controlView = null,
} = {}) {
  const overview = stateBundle?.overview ?? workflowStatus?.overview ?? null;
  const sessionReadiness = workflowStatus?.sessionReadiness
    ?? stateBundle?.workflowStatus?.sessionReadiness
    ?? stateBundle?.report?.sessionReadiness
    ?? null;
  return {
    stateBundle,
    workflowStatus,
    overview,
    controlView,
    report: stateBundle?.report ?? null,
    sessionReadiness,
    runReadiness: workflowStatus?.runReadiness ?? stateBundle?.report?.runReadiness ?? null,
    run: workflowStatus?.run ?? stateBundle?.report?.run ?? null,
    session: workflowStatus?.session ?? stateBundle?.report?.session ?? null,
    status: {
      lastAction: workflowStatus?.lastAction ?? overview?.status?.lastAction ?? null,
      error: workflowStatus?.error ?? overview?.status?.error ?? null,
      runStatus: workflowStatus?.run?.status ?? stateBundle?.report?.run?.status ?? null,
    },
  };
}

export function createMachineSessionReadonlyStatusApiManifest() {
  return {
    apiName: "machine-session-readonly-status",
    methods: {
      readStatus: {
        input: "{ getPanelApi, getControlView }",
        output: "readonly machine-session status snapshot",
      },
    },
    relatedControlPageMethods: [
      "loadSessionState",
      "readStatus",
      "refresh",
      "renderView",
    ],
    statusFields: [
      "stateBundle",
      "workflowStatus",
      "overview",
      "controlView",
      "report",
      "sessionReadiness",
      "runReadiness",
      "run",
      "session",
      "status",
    ],
  };
}

export function readMachineSessionReadonlyStatus({ getPanelApi, getControlView } = {}) {
  if (typeof getPanelApi !== "function") {
    throw new Error("A panel API getter is required.");
  }
  if (typeof getControlView !== "function") {
    throw new Error("A control view getter is required.");
  }

  const panelApi = getPanelApi();
  if (!panelApi) {
    return createMachineSessionReadonlyStatus();
  }
  return createMachineSessionReadonlyStatus({
    stateBundle: panelApi.getMachineSessionStateBundle?.() ?? null,
    workflowStatus: panelApi.getMachineSessionWorkflowStatus?.() ?? null,
    controlView: getControlView(),
  });
}
