/**
 * 统一填补法：计算每段在全局时间轴上的播放区间
 * - 分镜（segment）：严格 [audioStartTime, audioEndTime]
 * - 空镜（empty_shot）：
 *   - assignedStart = 上一段.audioEndTime（首段为 0）
 *   - assignedEnd = 下一段是空镜 ? 自己.audioEndTime : 下一段.audioStartTime
 */
export function computeAssignedIntervals(
  segs: Array<{
    id: number | string;
    type: string;
    audioStartTime?: number;
    audioEndTime?: number;
    actualDuration?: number;
    duration?: string | number;
  }>
): Record<string | number, { assignedStart: number; assignedEnd: number }> {
  const result: Record<string | number, { assignedStart: number; assignedEnd: number }> = {};
  for (let i = 0; i < segs.length; i++) {
    const seg = segs[i];
    if (seg.actualDuration === undefined) {
      throw new Error(`镜头 ${seg.id} 缺少时长数据，请返回第二步重新生成配音`);
    }
    const prev = i > 0 ? segs[i - 1] : null;
    const next = i < segs.length - 1 ? segs[i + 1] : null;
    if (seg.type === 'segment') {
      if (seg.audioStartTime === undefined || seg.audioEndTime === undefined) {
        throw new Error(`镜头 ${seg.id} 缺少打轴数据，请返回第二步重新生成配音`);
      }
      result[seg.id] = {
        assignedStart: seg.audioStartTime,
        assignedEnd: seg.audioEndTime,
      };
    } else {
      const assignedStart = prev ? prev.audioEndTime! : 0;
      let assignedEnd: number;
      if (next && next.type === 'empty_shot') {
        if (seg.audioEndTime === undefined) {
          throw new Error(`镜头 ${seg.id} 缺少打轴数据，请返回第二步重新生成配音`);
        }
        assignedEnd = seg.audioEndTime;
      } else if (next) {
        if (next.audioStartTime === undefined) {
          throw new Error(`镜头 ${next.id} 缺少打轴数据，请返回第二步重新生成配音`);
        }
        assignedEnd = next.audioStartTime;
      } else {
        if (seg.audioEndTime === undefined) {
          throw new Error(`镜头 ${seg.id} 缺少打轴数据，请返回第二步重新生成配音`);
        }
        assignedEnd = seg.audioEndTime;
      }
      result[seg.id] = { assignedStart, assignedEnd };
    }
  }
  return result;
}
