#!/usr/bin/env python3
"""Build index: aclnn api -> {header, md} for all interfaces in ifaces.txt"""
import os, re, json, sys

BASE = "/home/30039325/Vector_fuzz_cpp_testing"
INC = "/usr/local/Ascend/ascend-toolkit/latest/x86_64-linux/include/aclnnop"
OUT = "/tmp/opencode/op_index.json"

apis = [l.strip() for l in open("/tmp/opencode/ifaces.txt") if l.strip()]
api_set = set(apis)

# 1. header index: scan all headers for aclnnXxxGetWorkspaceSize declarations
header_index = {}
for fn in sorted(os.listdir(INC)):
    if not fn.endswith(".h"):
        continue
    fp = os.path.join(INC, fn)
    try:
        content = open(fp, encoding="utf-8", errors="ignore").read()
    except Exception:
        continue
    for m in re.finditer(r'aclnn(\w+?)GetWorkspaceSize\s*\(', content):
        api = "aclnn" + m.group(1)
        if api in api_set and api not in header_index:
            header_index[api] = fn

# 2. md index: ops-*/**/docs/*.md, filename tokens split by &
md_index = {}
for repo in ("ops-math", "ops-nn", "ops-cv", "ops-transformer"):
    d = os.path.join(BASE, repo)
    if not os.path.isdir(d):
        continue
    for root, dirs, files in os.walk(d):
        # experimental 目录排除(严谨:aclnn 资料不允许使用 experimental 目录下的接口文档)
        dirs[:] = [x for x in dirs if x.lower() != "experimental"]
        if not root.endswith("docs"):
            continue
        for f in files:
            if not f.endswith(".md"):
                continue
            stem = f[:-3]
            for tok in stem.split("&"):
                tok = tok.strip()
                if tok in api_set and tok not in md_index:
                    md_index[tok] = os.path.join(root, f)

index = {}
for api in apis:
    index[api] = {
        "header": header_index.get(api),
        "md": md_index.get(api),
    }

with open(OUT, "w") as f:
    json.dump(index, f, ensure_ascii=False, indent=1)

n_hdr = sum(1 for v in index.values() if v["header"])
n_md = sum(1 for v in index.values() if v["md"])
print(f"total={len(apis)} header_found={n_hdr} md_found={n_md} both_missing={sum(1 for v in index.values() if not v['header'] and not v['md'])}")
miss = [a for a in apis if not index[a]["header"]]
if miss:
    print("no-header apis (first 30):", miss[:30])