import type { ScriptShot } from '../types';

/**
 * 将后端返回的脚本生成结果标准化为前端 ScriptShot
 */
export function adaptScriptShots(data: unknown): ScriptShot[] {
  if (!Array.isArray(data)) {
    throw new Error('后端返回数据格式错误：期望数组');
  }

  return data.map((item: unknown, idx) => {
    if (!item || typeof item !== 'object') {
      return {
        id: idx + 1,
        type: 'segment' as const,
        scene: undefined,
        voiceover: '',
        duration: '5s',
      };
    }

    const raw = item as Record<string, unknown>;
    // 后端返回 duration 为 int（秒），统一转换为 "5s" 格式字符串
    let duration = '5s';
    let actualDuration = 5;
    if (typeof raw.duration === 'number') {
      const seconds = Math.max(1, Math.round(raw.duration));
      duration = `${seconds}s`;
      actualDuration = seconds;
    } else if (typeof raw.duration === 'string') {
      duration = raw.duration;
      actualDuration = parseFloat(raw.duration.replace(/[^0-9.]/g, '')) || 5;
    }
    return {
      id: typeof raw.id === 'number' ? raw.id : idx + 1,
      type: raw.type === 'empty_shot' ? 'empty_shot' : 'segment',
      scene: typeof raw.scene === 'string' ? raw.scene : undefined,
      voiceover: typeof raw.voiceover === 'string' ? raw.voiceover : '',
      duration,
      actualDuration,
    };
  });
}
