/**
 * 录音/ASR 共享状态
 *
 * 集中管理录音和实时 ASR 相关的响应式状态，
 * 供 useRealtimeRecording 和 main.js 共享使用
 */

import { ref, reactive } from "vue";

// ============== 录音状态 ==============
export const isRecording = ref(false);
export const isStoppingRecording = ref(false);
export const isPausingRecording = ref(false);
export const is_final = ref(false);
export const mediaRecorder = ref(null);
export const audioChunks = ref([]);
export const audioBlobURL = ref(null);
export const recordingTime = ref(0);
export const recordingInterval = ref(null);
export const canRecordAudio = ref(
  navigator.mediaDevices && navigator.mediaDevices.getUserMedia
);
export const canRecordSystemAudio = ref(false);
export const systemAudioSupported = ref(false);
export const systemAudioError = ref("");
export const recordingNotes = ref("");
export const showSystemAudioHelp = ref(false);

// ASR options for recording view
export const asrLanguage = ref(""); // Empty string for auto-detect
export const asrMinSpeakers = ref(""); // Empty string for auto-detect
export const asrMaxSpeakers = ref(""); // Empty string for auto-detect

// 音频可视化相关
export const audioContext = ref(null);
export const analyser = ref(null);
export const micAnalyser = ref(null);
export const systemAnalyser = ref(null);
export const visualizer = ref(null);
export const micVisualizer = ref(null);
export const systemVisualizer = ref(null);
export const animationFrameId = ref(null);

// 录音模式和流
export const recordingMode = ref("microphone"); // 'microphone', 'system', or 'both'
export const activeStreams = ref([]); // Track active streams for cleanup
export let systemStream = null;
export let micStream = null;

// ============== 录音大小监控 ==============
export const estimatedFileSize = ref(0);
export const fileSizeWarningShown = ref(false);
export const recordingQuality = ref("optimized"); // 'optimized', 'standard', 'high'
export const actualBitrate = ref(0);
export const maxRecordingMB = ref(200); // Maximum recording size before auto-stop
export const sizeCheckInterval = ref(null);

// ============== 草稿/暂停录音状态 ==============
export const isPaused = ref(false);
export const currentDraftId = ref(null);
export const pausedDuration = ref(0); // 暂停前的累计时长
export const pausedTranscription = ref(""); // 暂停前的转录文本
export const draftRecordings = ref([]); // 草稿列表
export const draftsExpanded = ref(true); // 草稿列表是否展开

// ============== 实时 ASR 状态 ==============
export let realtimeAsrPipeline = null;
export const asrResult = ref("");
export const asrResultOnline = ref("");
export const asrResultOffline = ref("");

// ============== 免责声明相关 ==============
export const showRecordingDisclaimerModal = ref(false);
export const pendingRecordingMode = ref(null);

// ============== 操作方法 ==============

/**
 * 重置录音状态
 */
export function resetRecordingState() {
  audioChunks.value = [];
  audioBlobURL.value = null;
  recordingNotes.value = "";
  activeStreams.value = [];
  recordingTime.value = 0;
  isStoppingRecording.value = false;
}

/**
 * 重置 ASR 状态
 */
export function resetASRState() {
  asrResult.value = "";
  asrResultOnline.value = "";
  asrResultOffline.value = "";
}

/**
 * 清理所有流和定时器
 */
export function cleanupRecording() {
  // 停止所有活动流
  activeStreams.value.forEach((stream) => {
    stream.getTracks().forEach((track) => track.stop());
  });
  activeStreams.value = [];

  // 关闭 AudioContext
  if (audioContext.value) {
    audioContext.value.close().catch((e) => {
      console.error("Error closing AudioContext:", e);
    });
    audioContext.value = null;
  }

  // 取消动画帧
  if (animationFrameId.value) {
    cancelAnimationFrame(animationFrameId.value);
    animationFrameId.value = null;
  }

  // 清除定时器
  if (recordingInterval.value) {
    clearInterval(recordingInterval.value);
    recordingInterval.value = null;
  }

  // 清除大小监控
  if (sizeCheckInterval.value) {
    clearInterval(sizeCheckInterval.value);
    sizeCheckInterval.value = null;
  }
}

/**
 * 开始录音前的状态初始化
 */
export function initRecordingState() {
  audioChunks.value = [];
  audioBlobURL.value = null;
  recordingNotes.value = "";
  activeStreams.value = [];

  // 重置音频流引用，避免上一次录音的旧流残留
  micStream = null;
  systemStream = null;

  // 清除标签和ASR选项
  // asrLanguage.value = ""; // 由调用方处理
  // asrMinSpeakers.value = "";
  // asrMaxSpeakers.value = "";

  // 重置草稿相关状态
  currentDraftId.value = null;
  isPaused.value = false;
  pausedDuration.value = 0;
  pausedTranscription.value = "";
  // resetRealtimeTranscript?.({ clearTimestampBarrier: true }); // 由调用方处理
  asrResult.value = "";
  asrResultOnline.value = "";
  asrResultOffline.value = "";
  recordingTime.value = 0;
  isStoppingRecording.value = false;
  // isEditingTranscription.value = false; // 由调用方处理

  // 确保计时器已停止，防止重复计时
  if (recordingInterval.value) {
    clearInterval(recordingInterval.value);
    recordingInterval.value = null;
  }
}

/**
 * 设置麦克风流
 */
export function setMicStream(stream) {
  micStream = stream;
}

/**
 * 设置系统音频流
 */
export function setSystemStream(stream) {
  systemStream = stream;
}

/**
 * 添加活动流
 */
export function addActiveStream(stream) {
  activeStreams.value.push(stream);
}

/**
 * 开始计时器
 */
export function startRecordingTimer() {
  // 先停止已有计时器，防止重复创建导致时间加速
  if (recordingInterval.value) {
    clearInterval(recordingInterval.value);
  }
  recordingInterval.value = setInterval(() => recordingTime.value++, 1000);
}

/**
 * 停止计时器
 */
export function stopRecordingTimer() {
  if (recordingInterval.value) {
    clearInterval(recordingInterval.value);
    recordingInterval.value = null;
  }
}

/**
 * 获取音频 Blob
 */
export function getAudioBlob() {
  if (audioChunks.value.length === 0) return null;
  return new Blob(audioChunks.value, { type: "audio/webm" });
}

/**
 * 丢弃录音 - 清理所有状态
 */
export function discardRecordingState() {
  audioChunks.value = [];
  audioBlobURL.value = null;
  isPaused.value = false;
  currentDraftId.value = null;
  pausedDuration.value = 0;
  pausedTranscription.value = "";
  recordingTime.value = 0;
  recordingNotes.value = "";
  asrResult.value = "";
  asrResultOnline.value = "";
  asrResultOffline.value = "";
  cleanupRecording();
}

// ============== 音频流工具函数 ==============

/**
 * 获取麦克风流
 */
export async function getMicrophoneStream() {
  const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
  micStream = stream;
  activeStreams.value.push(stream);
  return stream;
}

/**
 * 获取系统音频流
 */
export async function getSystemAudioStream() {
  const stream = await navigator.mediaDevices.getDisplayMedia({
    audio: true,
    video: true,
  });

  // 检查是否获得音频权限
  if (stream.getAudioTracks().length === 0) {
    stream.getVideoTracks().forEach((track) => track.stop());
    throw new Error(
      'System audio permission was not granted. Please ensure you check the "Share system audio" box.'
    );
  }

  systemStream = stream;
  activeStreams.value.push(stream);
  return stream;
}

/**
 * 合并麦克风和系统音频流
 */
export function combineAudioStreams(micStream, sysStream) {
  if (!audioContext.value) {
    audioContext.value = new (window.AudioContext || window.webkitAudioContext)();
  }

  const micSource = audioContext.value.createMediaStreamSource(micStream);
  const systemSource = audioContext.value.createMediaStreamSource(sysStream);
  const destination = audioContext.value.createMediaStreamDestination();

  micSource.connect(destination);
  systemSource.connect(destination);

  const mixedAudioTrack = destination.stream.getAudioTracks()[0];
  if (!mixedAudioTrack) {
    throw new Error("Failed to create mixed audio track");
  }

  return new MediaStream([mixedAudioTrack]);
}

/**
 * 从系统流创建纯音频流（去掉视频轨道）
 */
export function createAudioOnlyStream(sysStream) {
  const audioTracks = sysStream.getAudioTracks();
  if (audioTracks.length === 0) {
    throw new Error("System stream has no audio tracks");
  }
  return new MediaStream(audioTracks);
}

// ============== MediaRecorder 工具函数 ==============

/**
 * 获取优化的录音选项列表
 */
export function getRecorderOptionsList() {
  return [
    {
      mimeType: "audio/webm;codecs=opus",
      audioBitsPerSecond: 32000,
      description: "Optimized (32kbps Opus)",
    },
    {
      mimeType: "audio/webm;codecs=opus",
      audioBitsPerSecond: 64000,
      description: "Good quality (64kbps Opus)",
    },
    {
      mimeType: "audio/webm",
      audioBitsPerSecond: 64000,
      description: "Standard WebM (64kbps)",
    },
    {
      mimeType: "audio/mp4",
      audioBitsPerSecond: 64000,
      description: "Standard MP4 (64kbps)",
    },
    {
      mimeType: "audio/webm;codecs=opus",
      description: "Opus codec (default bitrate)",
    },
    {
      mimeType: "audio/webm",
      description: "WebM (default bitrate)",
    },
  ];
}

/**
 * 找到第一个支持的录音选项
 */
export function getFirstSupportedRecorderOption() {
  const optionsList = getRecorderOptionsList();
  for (const options of optionsList) {
    if (MediaRecorder.isTypeSupported(options.mimeType)) {
      return options;
    }
  }
  return null;
}

/**
 * 创建 MediaRecorder，带渐进式降级
 */
export function createMediaRecorderWithFallback(stream, onBitrateSet) {
  let mediaRecorderCreated = false;
  const options = getFirstSupportedRecorderOption();
  let attemptCount = 0;
  let bitrate = 128000;

  while (!mediaRecorderCreated && attemptCount < 5) {
    try {
      attemptCount++;

      if (options && attemptCount === 1) {
        mediaRecorder.value = new MediaRecorder(stream, options);
        bitrate = options.audioBitsPerSecond || 64000;
      } else if (options && attemptCount === 2 && options.audioBitsPerSecond) {
        mediaRecorder.value = new MediaRecorder(stream, {
          mimeType: options.mimeType,
        });
        bitrate = 128000;
      } else {
        mediaRecorder.value = new MediaRecorder(stream);
        bitrate = 128000;
      }

      mediaRecorderCreated = true;
    } catch (error) {
      console.warn(`MediaRecorder creation attempt ${attemptCount} failed:`, error);
      mediaRecorder.value = null;

      if (attemptCount >= 5) {
        throw new Error(`Failed to create MediaRecorder: ${error.message}`);
      }
    }
  }

  if (!mediaRecorder.value) {
    throw new Error("Failed to create MediaRecorder with any configuration");
  }

  // 更新比特率并调用回调
  actualBitrate.value = bitrate;
  if (onBitrateSet) {
    onBitrateSet(bitrate);
  }

  // 设置事件处理器
  mediaRecorder.value.ondataavailable = (event) => {
    audioChunks.value.push(event.data);
  };

  return mediaRecorder.value;
}

// ============== 可视化器工具函数 ==============

/**
 * 设置单轨可视化器
 */
export function setupSingleVisualizer(stream) {
  if (!audioContext.value) {
    audioContext.value = new (window.AudioContext || window.webkitAudioContext)();
  }

  analyser.value = audioContext.value.createAnalyser();
  analyser.value.fftSize = 256;
  const source = audioContext.value.createMediaStreamSource(stream);
  source.connect(analyser.value);
  return analyser.value;
}

/**
 * 设置双轨可视化器（麦克风和系统音频分开）
 */
export function setupDualVisualizer(micStream, sysStream) {
  if (!audioContext.value) {
    audioContext.value = new (window.AudioContext || window.webkitAudioContext)();
  }

  // 麦克风可视化器
  micAnalyser.value = audioContext.value.createAnalyser();
  micAnalyser.value.fftSize = 256;
  const micSource = audioContext.value.createMediaStreamSource(micStream);
  micSource.connect(micAnalyser.value);

  // 系统音频可视化器
  systemAnalyser.value = audioContext.value.createAnalyser();
  systemAnalyser.value.fftSize = 256;
  const systemSource = audioContext.value.createMediaStreamSource(sysStream);
  systemSource.connect(systemAnalyser.value);

  return { micAnalyser: micAnalyser.value, systemAnalyser: systemAnalyser.value };
}

// ============== 免责声明相关 ==============

/**
 * 显示免责声明
 */
export function showDisclaimer(mode) {
  pendingRecordingMode.value = mode;
  showRecordingDisclaimerModal.value = true;
}

/**
 * 接受免责声明
 */
export function acceptDisclaimer() {
  const mode = pendingRecordingMode.value;
  pendingRecordingMode.value = null;
  showRecordingDisclaimerModal.value = false;
  return mode;
}

/**
 * 取消免责声明
 */
export function cancelDisclaimer() {
  pendingRecordingMode.value = null;
  showRecordingDisclaimerModal.value = false;
}

// ============== 实时ASR管线 ==============

/**
 * 设置ASR管线实例
 */
export function setRealtimeAsrPipeline(pipeline) {
  realtimeAsrPipeline = pipeline;
}

/**
 * 获取ASR管线实例
 */
export function getRealtimeAsrPipeline() {
  return realtimeAsrPipeline;
}

/**
 * 停止ASR管线
 */
export async function stopRealtimeAsrPipeline() {
  if (realtimeAsrPipeline) {
    await realtimeAsrPipeline.stop();
  }
}
