import {
  getRunningWorkflowDefinition,
  getRunningWorkflowState
} from "../data/running-workflows";
import type {
  ScheduledConditionRecord
} from "../types";

export type ConditionStepTickerItem = {
  id: string;
  title: string;
  detail: string;
};

export type ConditionStepTickerView = {
  title: string;
  progressLabel: string;
  progressValue: number;
  currentStep: ConditionStepTickerItem | null;
};

export type TickerStackCard = {
  condition: ScheduledConditionRecord;
  view: ConditionStepTickerView;
  stackIndex: number;
};

const TICKER_STACK_DEPTH = 3;

export function selectTickerCondition(
  runningConditions: ScheduledConditionRecord[],
  rotationIndex: number
): ScheduledConditionRecord | null {
  if (runningConditions.length === 0) {
    return null;
  }

  return runningConditions[rotationIndex % runningConditions.length] ?? runningConditions[0] ?? null;
}

export function createVisibleTickerCards(
  runningConditions: ScheduledConditionRecord[],
  rotationIndex: number,
  nowMs: number
): TickerStackCard[] {
  if (runningConditions.length === 0) {
    return [];
  }

  const visibleCount = Math.min(runningConditions.length, TICKER_STACK_DEPTH);

  return Array.from({ length: visibleCount }, (_, stackIndex) => {
    const conditionIndex = (rotationIndex + stackIndex) % runningConditions.length;
    const condition = runningConditions[conditionIndex] ?? runningConditions[0];

    return {
      condition,
      view: createConditionStepView(condition, nowMs, runningConditions.length),
      stackIndex
    };
  });
}

function createConditionStepView(
  condition: ScheduledConditionRecord,
  nowMs: number,
  runningConditionCount: number
): ConditionStepTickerView {
  const workflow = getRunningWorkflowDefinition(condition);
  const workflowState = getRunningWorkflowState(condition, workflow, nowMs);
  const currentStep = workflow.steps[workflowState.currentStepIndex];
  const currentStepItem: ConditionStepTickerItem | null = currentStep
    ? {
        id: currentStep.id,
        title: `步骤 ${workflowState.currentStepIndex + 1}/${workflow.steps.length} ${currentStep.title}`,
        detail: currentStep.detail
      }
    : null;

  return {
    title: runningConditionCount > 1
      ? `${workflow.title} · ${condition.title} · ${runningConditionCount} 个执行中`
      : `${workflow.title} · ${condition.title}`,
    progressLabel: `${workflowState.progress}%`,
    progressValue: workflowState.progress,
    currentStep: currentStepItem
  };
}
