"""检索结果(repo/version/lang/path)到源文件 blob URL 的映射——源站领域知识
归 sources 层,ingest 只取用。"""

_BLOB_PREFIX = {
    "vllm": ("vllm-project/vllm", "docs"),
    "vllm-ascend": ("vllm-project/vllm-ascend", "docs/source"),
    "sglang": ("sgl-project/sglang", "docs"),
    "triton-ascend": ("triton-lang/triton-ascend", "docs"),
}


def url_for(repo: str, version: str, lang: str, path: str) -> str:
    """写入 meta_data.url 的源码 blob 链接:

    - GitHub 仓库:https://github.com/<org>/<repo>/blob/<version>/<语料 path 的 docs 前缀>/<path>
    - GitCode 仓库(repo 为 org/repo 形式):https://gitcode.com/<repo>/blob/<version>/docs/<path>
    - 昇腾官网产品(hiascend 爬取,repo 为产品 slug,无 org 层):
      https://www.hiascend.com/document/detail/<lang>/<产品>/<版本slug>/<path>;
      无版本维度的产品(Glossary/AscendFAQ)versionCode 恰等于产品名,URL 不含版本段;
      html 页转存的 .html.md 回溯时还原 .html(站点 URL 以原始后缀为准)
    - sglang 站内页面源文件是 .mdx(语料统一转存 .md),回溯时补后缀;
      shortcut: 远古 tag 的 .md 源会拼错,接受
    - gitcode 不支持 HEAD 作 ref(实测 404),故语料的分支版目录用真实分支名而非 "main"
    """
    if repo not in _BLOB_PREFIX:
        if "/" in repo:  # GitCode 仓库
            return f"https://gitcode.com/{repo}/blob/{version}/docs/{path}"
        # 昇腾官网产品;无版本维度的产品(versionCode==产品名)URL 少一段
        seg = f"{version}/" if version != repo else ""
        if path.endswith(".html.md"):  # html 页转存名,还原站点原始后缀
            path = path.removesuffix(".md")
        return f"https://www.hiascend.com/document/detail/{lang}/{repo}/{seg}{path}"
    if repo == "sglang" and (
        path == "index.md" or path.startswith(("docs/", "cookbook/"))
    ):
        path = path.removesuffix(".md") + ".mdx"
    if repo == "triton-ascend":  # 语料 path 相对 docs/en|zh,blob 路径要补语言层
        path = f"{lang}/{path}"
    org, prefix = _BLOB_PREFIX[repo]
    return f"https://github.com/{org}/blob/{version}/{prefix}/{path}"