const BASE_URL = 'https://www.xiaoyuzhoufm.com';
const PODCAST_PATH = '/podcast/';
const COLLECTION_PATH = '/collection/podcast/';
const EPISODE_PATH = '/episode/';

const NEXT_DATA_MARKER =
  '<script id="__NEXT_DATA__" type="application/json">';

/**
 * 根据合集 ID 拉取小宇宙页面的 __NEXT_DATA__ 原始数据。
 */
export async function fetchCollectionPayload(collectionId) {
  const url = `${BASE_URL}${COLLECTION_PATH}${collectionId}`;
  return fetchNextDataPayload(url, {
    entity: 'collection',
    sourceRef: collectionId,
  });
}

/**
 * 根据播客 ID 拉取小宇宙页面的 __NEXT_DATA__ 原始数据。
 */
export async function fetchPodcastPayload(podcastId) {
  const url = `${BASE_URL}${PODCAST_PATH}${podcastId}`;
  return fetchNextDataPayload(url, {
    entity: 'podcast',
    sourceRef: podcastId,
  });
}

/**
 * 根据节目 ID 拉取小宇宙页面的 __NEXT_DATA__ 原始数据。
 */
export async function fetchEpisodePayload(episodeId) {
  const url = `${BASE_URL}${EPISODE_PATH}${episodeId}`;
  return fetchNextDataPayload(url, {
    entity: 'episode',
    sourceRef: episodeId,
  });
}

/**
 * 请求页面并抽取 __NEXT_DATA__ 内容，返回带元信息的 payload。
 */
async function fetchNextDataPayload(url, meta) {
  const html = await requestText(url);
  try {
    const nextData = extractNextData(html);
    return {
      url,
      meta,
      nextData,
      pageProps: nextData?.props?.pageProps ?? {},
    };
  } catch (e) {
    const err = new Error(`${(e && e.message) || 'Failed to parse __NEXT_DATA__'} (${url})`);
    try { err.url = url; } catch (_) {}
    throw err;
  }
}

/**
 * 发送网络请求并返回 HTML 文本。
 */
async function requestText(url) {
  // 使用浏览器默认行为（不显式传递 credentials 或 UA）
  const response = await fetch(url);
  if (!response.ok) {
    const err = new Error(`Request failed with status ${response.status} (${url})`);
    try { err.url = url; err.status = response.status; } catch (_) {}
    throw err;
  }
  return response.text();
}

/**
 * 从 HTML 中提取并解析 __NEXT_DATA__ JSON。
 */
function extractNextData(html) {
  const start = html.indexOf(NEXT_DATA_MARKER);
  if (start === -1) {
    throw new Error('Missing __NEXT_DATA__ payload');
  }
  const from = start + NEXT_DATA_MARKER.length;
  const end = html.indexOf('</script>', from);
  if (end === -1) {
    throw new Error('Unable to locate __NEXT_DATA__ closing tag');
  }
  const jsonText = html.slice(from, end);
  try {
    return JSON.parse(jsonText);
  } catch (error) {
    throw new Error('Failed to parse __NEXT_DATA__ JSON');
  }
}
