/*!
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/**
 * Priority ordering of task instance states for visual display (segmented state
 * bar, tooltip breakdown). Failure/error states first, then active states
 * (running, deferred), then pending states (queued, scheduled), then terminal
 * states (success, skipped, removed).
 *
 * Keep in sync with state_priority in api_fastapi/common/parameters.py.
 */
export const STATE_PRIORITY: Array<string> = [
  "failed",
  "upstream_failed",
  "up_for_retry",
  "up_for_reschedule",
  "running",
  "restarting",
  "deferred",
  "awaiting_input",
  "queued",
  "scheduled",
  "success",
  "skipped",
  "removed",
];

/**
 * Sort child_states entries by priority (highest priority first) and filter out
 * entries with zero counts.  Unknown states are sorted to the end.
 */
export const sortStateEntries = (
  childStates: Record<string, number> | null | undefined,
): Array<[string, number]> => {
  if (!childStates) {
    return [];
  }

  return Object.entries(childStates)
    .filter(([, count]) => count > 0)
    .sort(([stateA], [stateB]) => {
      const idxA = STATE_PRIORITY.indexOf(stateA);
      const idxB = STATE_PRIORITY.indexOf(stateB);
      const priorityA = idxA === -1 ? STATE_PRIORITY.length : idxA;
      const priorityB = idxB === -1 ? STATE_PRIORITY.length : idxB;

      return priorityA - priorityB;
    });
};
