export interface DocManifestItem {
  title: string
  path: string
}

export interface DocManifest {
  docs: DocManifestItem[]
}

const docsBase = `${import.meta.env.BASE_URL}docs/`

function normalizeDocPath(path: string) {
  return path.replace(/^\/+/, '')
}

export function getDocsBase() {
  return docsBase
}

export async function getDocManifest() {
  const response = await fetch(`${docsBase}manifest.json`, { cache: 'no-cache' })
  if (!response.ok) {
    throw new Error('文档清单读取失败')
  }
  return response.json() as Promise<DocManifest>
}

export async function getDocContent(path: string) {
  const response = await fetch(`${docsBase}${encodeURI(normalizeDocPath(path))}`, { cache: 'no-cache' })
  if (!response.ok) {
    throw new Error('文档内容读取失败')
  }
  return response.text()
}
