All files / src/hooks connections.ts

28.34% Statements 89/314
14.47% Branches 22/152
25% Functions 20/80
29.05% Lines 86/296

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156                                                                                        330x   330x 330x   330x 1459x 181x     181x         330x               283x 283x 2058x   283x 283x 283x 1282x 1282x 1282x 1282x 1190x 600x   590x     1282x 1282x     283x                                                                                                                                                                                           28557x 28557x 28557x 28557x 28557x 28557x 28557x 28557x   28557x                                                                                                                                                                                                                                                                               4356x 4356x 4356x 4356x 4356x   4356x                                                                                                                                                                                             593x 593x 593x 593x 593x   593x           59x 11x         11x 11x     11x   11x   2x                             2x 9x                                   9x   9x                               9x                                 9x 9x         11x           11x         59x 11x                         263x 263x 2x                           3763x   3763x                                                       980x 980x 2x                           28557x 28557x 28557x 28557x   28557x                                                                             28557x 28557x 28557x 28557x   28557x                                                                                                                                                   33x                                                                                                             33x                                                                                                                                       33x                                                                                                                                                                                                                   33x                 33x                                                                                                                                                                                                                                                                                                                                                                    
import {
  useCurrentGroupId,
  useFlowsheetPorts,
  useFlowsheetUnitOps,
  useObjectsPortsMap,
  useStreamType,
} from "@/hooks/flowsheetObjects";
import { useProjectId } from "@/hooks/project";
import { useAppDispatch } from "@/store/hooks";
import { toast } from "sonner";
import {
  api,
  PortRead,
  DirectionEnum,
  SimulationObjectRead,
  useUnitopsPortsMergeStreamsCreateMutation,
  useUnitopsPortsSplitStreamCreateMutation,
  useUnitopsPortsPartialUpdateMutation,
  Port,
  useUnitopsPortsAddStreamCreateMutation,
  useUnitopsPortsConvertToDnCreateMutation,
  useUnitopsSimulationobjectsAddPortCreateMutation,
  useUnitopsSimulationobjectsMergeDecisionNodesCreateMutation,
  useUnitopsPortsRestoreConnectionsCreateMutation,
} from "../api/apiStore.gen";
 
import { useSearchParam } from "./searchParams";
import { isStream } from "../lib/isStream";
import { useUndoRedoStore } from "@/hooks/useUndoRedoStore";
import {
  createConnectCommand,
  createDisconnectCommand,
  createMergeStreamsCommand,
} from "@/utils/commandCreators";
import SuperJSON from "superjson";
import { useCallback } from "react";
import { AppDispatch, store } from "@/store/store";
 
/**
 * @returns Available ports for connection
 *   that is, those ports that are not connected to any stream or the connected stream is connected to only one port
 *   in the format of { availableInletPorts: [port1, port2, ...], availableOutletPorts: [port1, port2, ...] }
 */
export function useAvailablePortConnections() {
  const ports = useFlowsheetPorts();
 
  const availableInletPorts: PortRead[] = [];
  const availableOutletPorts: PortRead[] = [];
 
  ports?.forEach((port) => {
    if (!port.stream) {
      Iif (port.direction === DirectionEnum.Inlet) {
        availableInletPorts.push(port);
      } else {
        availableOutletPorts.push(port);
      }
    }
  });
 
  return { availableInletPorts, availableOutletPorts };
}
 
/**
 * @returns Available streams for connection
 *   in the format of { availableInletStreams: [stream1, stream2, ...], availableOutletStreams: [stream1, stream2, ...] }
 */
export function useAvailableStreamConnections() {
  const flowsheetObjects = useFlowsheetUnitOps();
  const objectsPortsMap = useObjectsPortsMap();
  const streams = flowsheetObjects?.filter((obj) => isStream(obj));
 
  const availableInletStreams: SimulationObjectRead[] = [];
  const availableOutletStreams: SimulationObjectRead[] = [];
  streams?.forEach((stream) => {
    const streamPorts = objectsPortsMap.get(stream.id)!;
    let newInlets = [stream];
    let newOutlets = [stream];
    streamPorts.forEach((port) => {
      if (port.direction === DirectionEnum.Inlet) {
        newInlets = [];
      } else {
        newOutlets = [];
      }
    });
    availableInletStreams.push(...newInlets);
    availableOutletStreams.push(...newOutlets);
  });
 
  return { availableInletStreams, availableOutletStreams };
}
 
/**
 * Predict merge behavior based on stream types and port directions
 * This implements the same logic as the backend merge_stream method
 */
function predictMergeBehavior(
  stream1: SimulationObjectRead,
  stream2: SimulationObjectRead,
  stream1Ports: Array<{
    id: number;
    direction?: string;
    unitOp?: number | null;
  }>,
  stream2Ports: Array<{
    id: number;
    direction?: string;
    unitOp?: number | null;
  }>,
  stream1TypeWasFeed: boolean,
) {
  // Determine stream types based on port connections
  const stream1ConnectedPortsCount = stream1Ports.length;
  const stream2ConnectedPortsCount = stream2Ports.length;
 
  // Get the first port to determine direction (assumes single port per stream for feed/product)
  const stream1Port = stream1Ports[0];
  const stream2Port = stream2Ports[0];
 
  // Case 2: Connecting intermediate stream with product or feed
  Iif (stream1ConnectedPortsCount > 1 || stream2ConnectedPortsCount > 1) {
    // One or both streams are intermediate - creates decision node, both streams survive
    return {
      mergeType: "decision_node" as const,
      stream1WillBeDeleted: false,
      stream2WillBeDeleted: false,
      resultingStreamId: stream2.id, // Convention: use stream2 for decision node scenarios
      deletedStreamId: stream1.id, // Not actually deleted, just placeholder
      logic:
        "Intermediate stream merge - creates decision node, both streams survive",
    };
  }
 
  // Case 3: Feed to feed or product to product (same direction)
  Iif (stream1Port?.direction === stream2Port?.direction) {
    // Parallel merge - creates decision node, both streams survive
    return {
      mergeType: "parallel" as const,
      stream1WillBeDeleted: false,
      stream2WillBeDeleted: false,
      resultingStreamId: stream2.id, // Convention: use stream2 for parallel scenarios
      deletedStreamId: stream1.id, // Not actually deleted, just placeholder
      logic:
        "Parallel merge (same direction) - creates decision node, both streams survive",
    };
  }
 
  // Case 4: Feed to product or product to feed (most common case)
  // Based on backend logic: always preserve outlet stream, delete inlet stream
  let inletStream: SimulationObjectRead;
  let outletStream: SimulationObjectRead;
  let inletWillBeDeleted: boolean;
  let outletWillBeDeleted: boolean;
 
  if (stream1Port?.direction === "inlet") {
    inletStream = stream1;
    outletStream = stream2;
    inletWillBeDeleted = true;
    outletWillBeDeleted = false;
  } else {
    inletStream = stream2;
    outletStream = stream1;
    inletWillBeDeleted = stream1Port?.direction === "outlet" ? false : true;
    outletWillBeDeleted = stream1Port?.direction === "outlet" ? true : false;
  }
 
  return {
    mergeType: "simple" as const,
    stream1WillBeDeleted:
      stream1.id === inletStream.id ? inletWillBeDeleted : outletWillBeDeleted,
    stream2WillBeDeleted:
      stream2.id === inletStream.id ? inletWillBeDeleted : outletWillBeDeleted,
    resultingStreamId: outletStream.id,
    deletedStreamId: inletStream.id,
    logic: `Simple merge: outlet stream (${outletStream.id}) preserved, inlet stream (${inletStream.id}) deleted`,
  };
}
 
/**
 * Connect two material streams together
 * @returns A function that connects two material streams
 */
export function useMergeStreams() {
  const [mergeStreamsMutation] = useUnitopsPortsMergeStreamsCreateMutation();
  const objectsPortsMap = useObjectsPortsMap();
  const [, setObjectId] = useSearchParam("object");
  const dispatch = useAppDispatch();
  const flowsheetId = useProjectId();
  const streamType = useStreamType();
  const groupId = useCurrentGroupId();
  const { addHistory } = useUndoRedoStore();
 
  return (
    activeObject: SimulationObjectRead,
    overObject: SimulationObjectRead,
  ) => {
    const activeStreamType = streamType(activeObject.id);
    const activeStreamTypeWasFeed = activeStreamType === "feed";
 
    // Collect required data for command creation BEFORE the operation
    const stream1Ports = objectsPortsMap.get(activeObject.id) || [];
    const stream2Ports = objectsPortsMap.get(overObject.id) || [];
 
    // Get graphic objects data for position tracking
    const graphicsState = api.endpoints.graphicsObjectsList.select({
      group: groupId,
    });
    const graphicsData = graphicsState(store.getState()).data || [];
 
    const stream1Graphics = graphicsData.filter(
      (g) => g.simulationObject === activeObject.id,
    );
    const stream2Graphics = graphicsData.filter(
      (g) => g.simulationObject === overObject.id,
    );
 
    // Prepare data in the format expected by createMergeStreamsCommand
    const stream1PortConnections = stream1Ports.map((port) => ({
      portId: port.id,
      unitOpId: port.unitOp || 0,
      direction: port.direction || "",
      key: port.key || "",
    }));
 
    const stream2PortConnections = stream2Ports.map((port) => ({
      portId: port.id,
      unitOpId: port.unitOp || 0,
      direction: port.direction || "",
      key: port.key || "",
    }));
 
    const stream1GraphicPositions = stream1Graphics.map((graphic) => ({
      x: graphic.x || 0,
      y: graphic.y || 0,
      width: graphic.width || 100,
      height: graphic.height || 50,
      groupId: graphic.group || groupId,
    }));
 
    const stream2GraphicPositions = stream2Graphics.map((graphic) => ({
      x: graphic.x || 0,
      y: graphic.y || 0,
      width: graphic.width || 100,
      height: graphic.height || 50,
      groupId: graphic.group || groupId,
    }));
 
    // Note: feedType update removed as it's not part of GraphicObjectRead interface
 
    // Predict merge behavior BEFORE performing the operation
    const mergeAnalysis = predictMergeBehavior(
      activeObject,
      overObject,
      stream1Ports,
      stream2Ports,
      activeStreamTypeWasFeed,
    );
 
    mergeStreamsMutation({
      mergeStreams: {
        stream1: activeObject.id,
        stream2: overObject.id,
      },
    })
      .unwrap()
      .then(async () => {
        // Create command with predicted deletion flags
        const mergeCommand = createMergeStreamsCommand({
          stream1: activeObject,
          stream2: overObject,
          stream1PortConnections,
          stream2PortConnections,
          stream1GraphicPositions,
          stream2GraphicPositions,
          stream1TypeWasFeed: activeStreamTypeWasFeed,
          mergeType: mergeAnalysis.mergeType,
          stream1WasDeleted: mergeAnalysis.stream1WillBeDeleted,
          stream2WasDeleted: mergeAnalysis.stream2WillBeDeleted,
        });
 
        // Set result metadata based on predictions
        mergeCommand.resultingStreamId = mergeAnalysis.resultingStreamId;
        mergeCommand.deletedStreamId = mergeAnalysis.deletedStreamId;
 
        console.log("Merge command created with predictions:", {
          mergeType: mergeAnalysis.mergeType,
          stream1WasDeleted: mergeCommand.stream1WasDeleted,
          stream2WasDeleted: mergeCommand.stream2WasDeleted,
          resultingStreamId: mergeCommand.resultingStreamId,
          logic: mergeAnalysis.logic,
        });
 
        addHistory(mergeCommand);
 
        toast.success("Successfully connected material streams");
      })
      .catch((error) => {
        // Handle different error structures safely
        const errorMessage =
          error?.data?.message || error?.message || "Unknown error occurred";
        toast.error(`Failed to connect material streams: ${errorMessage}`);
        console.error("Merge streams error:", error);
        // Don't add to history if operation failed
      });
  };
}
 
/**
 * Splits an intermediate stream into two streams
 * @param objectId The ID of the stream to split
 * @returns A function that splits the stream
 */
export function useSplitStream() {
  const [splitStream] = useUnitopsPortsSplitStreamCreateMutation();
  return (objectId: number) => {
    splitStream({
      splitStream: {
        stream: objectId,
      },
    });
  };
}
 
/**
 * Splits an intermediate stream with undo/redo tracking
 * This captures the split operation information for proper undo functionality
 */
export function useSplitStreamWithHistory() {
  const [splitStreamMutation] = useUnitopsPortsSplitStreamCreateMutation();
  const dispatch = useAppDispatch();
  const flowsheetId = useProjectId();
  const { addHistory } = useUndoRedoStore();
  const ports = useFlowsheetPorts();
 
  return async (streamId: number) => {
    try {
      // Get the current state before splitting
      const connectedPorts = ports?.filter((p) => p.stream === streamId) || [];
 
      Iif (connectedPorts.length !== 2) {
        console.warn(
          "Split stream called on stream that is not intermediate:",
          streamId,
          "Connected ports:",
          connectedPorts.length,
        );
        // Fallback to simple split without history
        return splitStreamMutation({
          splitStream: { stream: streamId },
        }).unwrap();
      }
 
      const [port1, port2] = connectedPorts;
 
      // Capture the original connection data
      const originalConnectionData = {
        originalStreamId: streamId,
        port1: { ...port1 },
        port2: { ...port2 },
        connectedPorts: connectedPorts.map((p) => ({ ...p })),
      };
 
      // Perform the split operation
      const response = await splitStreamMutation({
        splitStream: { stream: streamId },
      }).unwrap();
 
      // Get the new state after splitting to capture new stream IDs
      const updatedPorts = await dispatch(
        api.endpoints.unitopsPortsList.initiate({
          flowsheet: flowsheetId!,
        }),
      ).unwrap();
 
      const newPort1 = updatedPorts.find((p) => p.id === port1.id);
      const newPort2 = updatedPorts.find((p) => p.id === port2.id);
 
      if (newPort1 && newPort2 && newPort1.stream && newPort2.stream) {
        // Create disconnect command with split tracking information
        const disconnectCommand = createDisconnectCommand({
          portId1: port1.id,
          objectId1: port1.unitOp || 0,
          portId2: port2.id,
          objectId2: port2.unitOp || 0,
          streamId: streamId,
          connectionData: originalConnectionData,
          wasSplitOperation: true,
          originalStreamId: streamId,
          newStreamIds: [newPort1.stream, newPort2.stream],
          portStreamMapping: {
            [port1.id]: newPort1.stream,
            [port2.id]: newPort2.stream,
          },
        });
 
        addHistory(disconnectCommand);
 
        // Note: Stream ID mapping is now handled within the disconnect command data
 
        console.log("Split stream with history tracking:", {
          original: streamId,
          newStreams: [newPort1.stream, newPort2.stream],
          portMapping: {
            [port1.id]: newPort1.stream,
            [port2.id]: newPort2.stream,
          },
        });
      } else {
        console.warn(
          "Could not determine new stream IDs after split operation",
        );
      }
 
      return response;
    } catch (error) {
      console.error("Failed to split stream with history:", error);
      throw error;
    }
  };
}
 
/**
 * Disconnects or changes the connection of a port
 * @param portId The ID of the port to disconnect
 * @param patchedPort The new port data (eg. { stream: null} to disconnect)
 * @param skipHistory Optional parameter to skip adding to undo history (for restoration operations)
 * @returns A function that disconnects the port
 */
export function useUpdatePort() {
  const [updatePort] = useUnitopsPortsPartialUpdateMutation();
  const dispatch = useAppDispatch();
  const flowsheetId = useProjectId();
  const { addHistory } = useUndoRedoStore();
  const ports = useFlowsheetPorts();
 
  return (
    portId: number,
    patchedPort: Partial<Port>,
    skipHistory: boolean = false,
  ) => {
    // Get the current port state before making changes
    const currentPort = ports?.find((p) => p.id === portId);
    Iif (!currentPort) {
      console.error("Port not found:", portId);
      return;
    }
 
    const oldStreamId = currentPort.stream;
    const newStreamId = patchedPort.stream;
 
    // Only add to history if skipHistory is false
    if (!skipHistory) {
      // Create undo/redo command based on the type of operation
      if (oldStreamId && newStreamId === null) {
        // Disconnecting: create disconnect command
        const disconnectCommand = createDisconnectCommand({
          portId1: portId,
          objectId1: currentPort.unitOp || 0,
          portId2: portId, // For single port operations, use same port
          objectId2: currentPort.unitOp || 0,
          streamId: oldStreamId,
          connectionData: {
            port: currentPort,
            oldConnection: {
              portId: portId,
              streamId: oldStreamId,
              unitOpId: currentPort.unitOp,
            },
          },
        });
        addHistory(disconnectCommand);
      I} else if (!oldStreamId && newStreamId) {
        // Connecting: create connect command
        const connectCommand = createConnectCommand({
          portId1: portId,
          objectId1: currentPort.unitOp || 0,
          portId2: portId, // For single port operations, use same port
          objectId2: currentPort.unitOp || 0,
          streamId: newStreamId,
          connectionData: {
            port: currentPort,
            newConnection: {
              portId: portId,
              streamId: newStreamId,
              unitOpId: currentPort.unitOp,
            },
          },
        });
        addHistory(connectCommand);
      } else if (oldStreamId && newStreamId && oldStreamId !== newStreamId) {
        // Changing connection: create disconnect command for old, then connect command for new
        const disconnectCommand = createDisconnectCommand({
          portId1: portId,
          objectId1: currentPort.unitOp || 0,
          portId2: portId,
          objectId2: currentPort.unitOp || 0,
          streamId: oldStreamId,
          connectionData: {
            port: currentPort,
            oldConnection: {
              portId: portId,
              streamId: oldStreamId,
              unitOpId: currentPort.unitOp,
            },
          },
        });
 
        const connectCommand = createConnectCommand({
          portId1: portId,
          objectId1: currentPort.unitOp || 0,
          portId2: portId,
          objectId2: currentPort.unitOp || 0,
          streamId: newStreamId,
          connectionData: {
            port: currentPort,
            newConnection: {
              portId: portId,
              streamId: newStreamId,
              unitOpId: currentPort.unitOp,
            },
          },
        });
 
        // Add both commands to history
        addHistory(disconnectCommand);
        addHistory(connectCommand);
      }
    }
 
    // Perform the actual update
    updatePort({
      id: portId,
      patchedPort: patchedPort,
    });
 
    // Update the cache optimistically
    dispatch(
      api.util.updateQueryData(
        "unitopsPortsList",
        { flowsheet: flowsheetId },
        (cachedPorts) => {
          const p = cachedPorts.find((p) => p.id === portId)!;
          Object.assign(p, patchedPort);
        },
      ),
    );
  };
}
 
/**
 * Adds a stream to a port
 * @param portId The ID of the port to add a stream to
 * @returns A function that adds a stream to a port
 */
export function useAddStream() {
  const [addStream] = useUnitopsPortsAddStreamCreateMutation();
  return (portId: number) => {
    addStream({
      addStream: {
        port: portId,
      },
    });
  };
}
 
/**
 * Converts a stream to a decision node
 * @param streamId The ID of the stream to convert
 * @returns A function that converts a stream to a decision node
 */
export function useConvertStreamToDn() {
  const [convertToDn] = useUnitopsPortsConvertToDnCreateMutation();
 
  return (streamId: number) => {
    convertToDn({
      convertToDn: {
        stream: streamId,
      },
      // stream: streamId
    })
      .unwrap()
      .then((response) => {
        toast.success(
          "Successfully converted material stream to decision node",
        );
      })
      .catch((error) => {
        toast.error(
          `Failed to connect material streams: ${error.data.message}`,
        );
      });
  };
}
 
/**
 * Adds a port to a simulation object
 * @param simulationObjectId The ID of the simulation object to add a port to
 * @param key The key of the port to add
 * @returns A function that adds a port to a simulation object
 */
export function useAddPort() {
  const [addPort] = useUnitopsSimulationobjectsAddPortCreateMutation();
  return (simulationObjectId: number, key: string) => {
    addPort({
      addPort: {
        simulationObjectId: simulationObjectId,
        key: key,
      },
    });
  };
}
 
/**
 * Hook to add a port to a unit operation and connect a stream to it
 * @returns A function that adds a port and connects a stream
 */
export function useAddPortAndConnectStream() {
  const [addPort] = useUnitopsSimulationobjectsAddPortCreateMutation();
  const dispatch = useAppDispatch();
  const flowsheetId = useProjectId();
  const streamType = useStreamType();
 
  return (unitOp: SimulationObjectRead, stream: SimulationObjectRead) => {
    // Determine the port type based on the unit op type
    let portKey = "inlet"; // default
 
    if (unitOp.objectType === "decisionNode") {
      // For decision nodes, determine port based on stream type
      portKey = streamType(stream.id) === "feed" ? "outlet" : "inlet"; //feed streams are outlet and product streams are inlet
    } else if (unitOp.objectType === "mixer") {
      portKey = "inlet";
    I} else if (unitOp.objectType === "splitter") {
      portKey = "outlet";
    }
 
    // Add the port with stream
    addPort({
      addPort: {
        simulationObjectId: unitOp.id,
        key: portKey,
        stream: stream.id,
      },
    })
      .unwrap()
      .then(() => {
        toast.success("Successfully added port and connected stream");
      })
      .catch((error) => {
        toast.error(
          `Failed to add port and connect stream: ${error.data?.message || "Unknown error"}`,
        );
      });
  };
}
 
/**
 * Merges two decision nodes
 * @returns A function that merges two decision nodes
 */
export function useMergeDecisionNodes() {
  const [mergeDecisionNodes] =
    useUnitopsSimulationobjectsMergeDecisionNodesCreateMutation();
  const dispatch = useAppDispatch();
  const flowsheetId = useProjectId();
  const [, setObjectId] = useSearchParam("object");
 
  return (
    decisionNodeActive: SimulationObjectRead,
    decisionNodeOver: SimulationObjectRead,
  ) => {
    // Switch selected object to the target node since active will be removed
    setObjectId(decisionNodeOver.id);
 
    //TODO: add optimistic updates for graphics and simulation objects in future
 
    mergeDecisionNodes({
      mergeDecisionNodes: {
        decisionNodeActive: decisionNodeActive.id,
        decisionNodeOver: decisionNodeOver.id,
      },
    })
      .unwrap()
      .then(() => {
        toast.success("Successfully merged decision nodes");
      })
      .catch((error) => {
        toast.error(
          `Failed to merge decision nodes: ${error.data?.message || "Unknown error"}`,
        );
      });
  };
}
 
// Type for connection restoration results
interface ConnectionRestoreResult {
  success: boolean;
  portId: number;
  streamId: number | null;
  error?: string;
}
 
// Type for backend restore connections response
interface RestoreConnectionsResponse {
  status: "success" | "failed";
  restored_count: number;
  total_connections: number;
  failed_connections?: Array<{
    portId: number;
    streamId: number | null;
    error: string;
    retry_recommended?: boolean;
  }>;
  skipped_connections?: Array<{
    portId: number;
    streamId: number | null;
    reason: string;
  }>;
  retry_candidates?: Array<{
    portId: number;
    streamId: number | null;
    error: string;
    retry_recommended: boolean;
  }>;
}
 
// 🆕 Types for enhanced validation system
interface ConnectionData {
  portId: number;
  streamId: number | null;
  serializedConnection: string;
  validationError?: string;
}
 
interface RestoreValidationResult {
  valid: ConnectionData[];
  invalid: ConnectionData[];
  delayed: ConnectionData[];
}
 
// 🆕 Enhanced validation system
const validateConnectionsForRestoration = async (
  connectionData: ConnectionData[],
  flowsheetId: number,
  dispatch: AppDispatch,
): Promise<RestoreValidationResult> => {
  console.log(
    `🔍 Validating ${connectionData.length} connections for restoration...`,
  );
 
  // 🆕 Force fresh data from backend
  dispatch(
    api.util.invalidateTags(["SimulationObjects" as never, "Ports" as never]),
  );
 
  const [freshPorts, freshObjects] = await Promise.all([
    dispatch(
      api.endpoints.unitopsPortsList.initiate({ flowsheet: flowsheetId }),
    ).unwrap(),
    dispatch(
      api.endpoints.unitopsSimulationobjectsList.initiate({
        flowsheet: flowsheetId,
      }),
    ).unwrap(),
  ]);
 
  const valid: ConnectionData[] = [];
  const invalid: ConnectionData[] = [];
  const delayed: ConnectionData[] = [];
 
  connectionData.forEach((conn) => {
    const { portId, streamId } = conn;
    const portExists = freshPorts.find((p) => p.id === portId);
    const streamExists = streamId
      ? freshObjects.find((o) => o.id === streamId)
      : true;
 
    if (!portExists) {
      invalid.push({ ...conn, validationError: `Port ${portId} not found` });
    } else if (streamId && !streamExists) {
      delayed.push({
        ...conn,
        validationError: `Stream ${streamId} not ready`,
      });
    } else {
      valid.push(conn);
    }
  });
 
  console.log(
    `🔍 Validation results: ${valid.length} valid, ${invalid.length} invalid, ${delayed.length} delayed`,
  );
  return { valid, invalid, delayed };
};
 
// 🆕 Retry logic with exponential backoff
const retryWithBackoff = async (
  connections: ConnectionData[],
  maxAttempts: number,
  baseDelay: number,
  flowsheetId: number,
  dispatch: AppDispatch,
  restoreConnections: (
    connections: ConnectionData[],
  ) => Promise<ConnectionRestoreResult[]>,
): Promise<ConnectionRestoreResult[]> => {
  let remainingConnections = [...connections];
  let attempts = 0;
  const results: ConnectionRestoreResult[] = [];
 
  while (remainingConnections.length > 0 && attempts < maxAttempts) {
    attempts++;
    const delay = baseDelay * Math.pow(2, attempts - 1); // Exponential backoff
 
    console.log(
      `🔄 Retry attempt ${attempts}/${maxAttempts} for ${remainingConnections.length} connections (delay: ${delay}ms)`,
    );
 
    Iif (attempts > 1) {
      await new Promise((resolve) => setTimeout(resolve, delay));
    }
 
    try {
      // Re-validate before retry
      const revalidation = await validateConnectionsForRestoration(
        remainingConnections,
        flowsheetId,
        dispatch,
      );
 
      Iif (revalidation.valid.length > 0) {
        const attemptResults = await restoreConnections(revalidation.valid);
        results.push(...attemptResults);
 
        // Remove successful connections from retry list
        const successfulPortIds = new Set(
          attemptResults.filter((r) => r.success).map((r) => r.portId),
        );
        remainingConnections = remainingConnections.filter(
          (conn) => !successfulPortIds.has(conn.portId),
        );
      }
 
      // Update remaining connections (delayed connections might become valid)
      remainingConnections = [...revalidation.delayed, ...revalidation.invalid];
    } catch (error) {
      console.error(`❌ Retry attempt ${attempts} failed:`, error);
    }
  }
 
  // Add final failures
  remainingConnections.forEach((conn) => {
    results.push({
      success: false,
      portId: conn.portId,
      streamId: conn.streamId,
      error: `Failed after ${maxAttempts} retry attempts`,
    });
  });
 
  return results;
};
 
// 🆕 Core restoration function
const restoreConnectionsCore = async (
  connections: ConnectionData[],
  restoreConnectionsMutation: ReturnType<
    typeof useUnitopsPortsRestoreConnectionsCreateMutation
  >[0],
): Promise<ConnectionRestoreResult[]> => {
  try {
    // Transform the connection data to match the backend format
    const transformedConnections = connections.map(
      ({ portId, streamId, serializedConnection }) => ({
        portId,
        streamId,
        serializedConnection,
      }),
    );
 
    // Call the specialized restore endpoint and get the actual response
    const backendResponse = (await restoreConnectionsMutation({
      restoreConnections: {
        connections: transformedConnections,
      },
    }).unwrap()) as RestoreConnectionsResponse;
 
    // Parse the actual backend response format
    const results: ConnectionRestoreResult[] = [];
 
    // Create a map for quick lookup of original connection data
    const connectionMap = new Map(
      connections.map((conn) => [conn.portId, conn]),
    );
 
    // Handle successful connections based on restored_count
    // Note: Backend doesn't specify which connections succeeded, so we assume the first N
    Iif (backendResponse.restored_count > 0) {
      for (
        let i = 0;
        i < Math.min(backendResponse.restored_count, connections.length);
        i++
      ) {
        const conn = connections[i];
        results.push({
          success: true,
          portId: conn.portId,
          streamId: conn.streamId,
        });
      }
    }
 
    // Handle explicitly failed connections
    Iif (backendResponse.failed_connections) {
      backendResponse.failed_connections.forEach((failure) => {
        const originalConn = connectionMap.get(failure.portId);
        results.push({
          success: false,
          portId: failure.portId,
          streamId: failure.streamId || (originalConn?.streamId ?? null),
          error: failure.error || "Connection failed",
        });
      });
    }
 
    // Handle skipped connections
    Iif (backendResponse.skipped_connections) {
      backendResponse.skipped_connections.forEach((skipped) => {
        const originalConn = connectionMap.get(skipped.portId);
        results.push({
          success: false,
          portId: skipped.portId,
          streamId: skipped.streamId || (originalConn?.streamId ?? null),
          error: skipped.reason || "Connection skipped",
        });
      });
    }
 
    // Handle any remaining connections that weren't accounted for
    // (in case restored_count + failed + skipped < total)
    const processedPortIds = new Set(results.map((r) => r.portId));
    connections.forEach((conn) => {
      Iif (!processedPortIds.has(conn.portId)) {
        results.push({
          success: false,
          portId: conn.portId,
          streamId: conn.streamId,
          error: "Connection status unknown",
        });
      }
    });
 
    console.log(
      `Backend response: ${backendResponse.restored_count}/${backendResponse.total_connections} connections restored`,
    );
    return results;
  } catch (error: unknown) {
    console.error("Restoration attempt failed:", error);
 
    // Create error results for all connections
    return connections.map(({ portId, streamId }) => ({
      success: false,
      portId,
      streamId,
      error: error instanceof Error ? error.message : "Unknown error",
    }));
  }
};
 
// 🆕 Enhanced Logging & Performance Monitoring System
const logConnectionOperation = (operation: string, data: unknown) => {
  console.log(`[Connection-${operation}]`, {
    timestamp: new Date().toISOString(),
    operation,
    data,
    stack: new Error().stack?.split("\n").slice(1, 4),
  });
};
 
const measurePerformance = async <T>(
  operation: string,
  fn: () => Promise<T>,
): Promise<T> => {
  const start = performance.now();
  try {
    const result = await fn();
    const duration = performance.now() - start;
    console.log(`⏱️ ${operation} completed in ${duration.toFixed(2)}ms`);
    logConnectionOperation("performance", {
      operation,
      duration,
      success: true,
    });
    return result;
  } catch (error) {
    const duration = performance.now() - start;
    console.error(
      `❌ ${operation} failed after ${duration.toFixed(2)}ms:`,
      error,
    );
    logConnectionOperation("performance", {
      operation,
      duration,
      success: false,
      error,
    });
    throw error;
  }
};
 
/**
 * Hook for restoring connections during undo operations without creating new undo history
 * This uses the specialized restore-connections endpoint that bypasses recycle tear creation
 * 🆕 ENHANCED: Now includes pre-restoration validation and retry logic
 */
export function useDirectConnectionRestore() {
  const [restoreConnectionsMutation] =
    useUnitopsPortsRestoreConnectionsCreateMutation();
  const dispatch = useAppDispatch();
  const flowsheetId = useProjectId();
 
  return useCallback(
    async (
      connectionData: Array<{
        portId: number;
        streamId: number | null;
        serializedConnection: string;
      }>,
    ): Promise<ConnectionRestoreResult[]> => {
      Iif (!connectionData || connectionData.length === 0) {
        console.log("No connection data to restore");
        return [];
      }
 
      return measurePerformance(
        `connection-restoration-${connectionData.length}-connections`,
        async () => {
          console.log(
            `🔄 Starting enhanced restoration of ${connectionData.length} connections...`,
          );
          logConnectionOperation("restore-start", {
            connectionCount: connectionData.length,
          });
 
          // 🆕 Pre-restoration validation
          const validation = await measurePerformance(
            "pre-validation",
            async () =>
              validateConnectionsForRestoration(
                connectionData,
                flowsheetId!,
                dispatch,
              ),
          );
 
          Iif (validation.invalid.length > 0) {
            console.warn(
              `❌ ${validation.invalid.length} connections permanently invalid:`,
              validation.invalid,
            );
            logConnectionOperation("validation-failed", {
              invalidCount: validation.invalid.length,
              invalid: validation.invalid,
            });
          }
 
          const allResults: ConnectionRestoreResult[] = [];
 
          // 🆕 Process valid connections immediately
          Iif (validation.valid.length > 0) {
            const validResults = await measurePerformance(
              `restore-valid-${validation.valid.length}`,
              async () =>
                restoreConnectionsCore(
                  validation.valid,
                  restoreConnectionsMutation,
                ),
            );
            allResults.push(...validResults);
          }
 
          // 🆕 Retry delayed connections
          Iif (validation.delayed.length > 0) {
            console.log(
              `⏳ Retrying ${validation.delayed.length} delayed connections...`,
            );
            const retryResults = await measurePerformance(
              `retry-delayed-${validation.delayed.length}`,
              async () =>
                retryWithBackoff(
                  validation.delayed,
                  3, // maxAttempts
                  500, // baseDelay in ms
                  flowsheetId!,
                  dispatch,
                  (connections) =>
                    restoreConnectionsCore(
                      connections,
                      restoreConnectionsMutation,
                    ),
                ),
            );
            allResults.push(...retryResults);
          }
 
          // 🆕 Add failed results for invalid connections
          validation.invalid.forEach((conn) => {
            allResults.push({
              success: false,
              portId: conn.portId,
              streamId: conn.streamId,
              error: conn.validationError,
            });
          });
 
          // Update cache to reflect successful changes
          Iif (flowsheetId) {
            const successfulConnections = allResults.filter((r) => r.success);
            Iif (successfulConnections.length > 0) {
              await measurePerformance("cache-update", async () => {
                dispatch(
                  api.util.updateQueryData(
                    "unitopsPortsList",
                    { flowsheet: flowsheetId },
                    (cachedPorts) => {
                      successfulConnections.forEach(({ portId, streamId }) => {
                        const port = cachedPorts.find((p) => p.id === portId);
                        Iif (port) {
                          port.stream = streamId;
                        }
                      });
                    },
                  ),
                );
              });
            }
          }
 
          const successCount = allResults.filter((r) => r.success).length;
          console.log(
            `✅ Enhanced restoration complete: ${successCount}/${allResults.length} successful`,
          );
          logConnectionOperation("restore-complete", {
            total: allResults.length,
            successful: successCount,
            failed: allResults.length - successCount,
            successRate:
              ((successCount / allResults.length) * 100).toFixed(1) + "%",
          });
 
          return allResults;
        },
      );
    },
    [restoreConnectionsMutation, dispatch, flowsheetId],
  );
}