File size: 21,362 Bytes
1d27ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
#!/usr/bin/env python3
from __future__ import annotations

import csv
import io
import json
import os
import re
import unicodedata
from collections import Counter, defaultdict
from pathlib import Path


MS_CSV = Path("/mnt/disk1/yanganqi/QQCM/MS/三者并集完整输出.csv")
OUTPUT_CSV = Path("/mnt/disk1/yanganqi/QQCM/MS/三者并集完整输出_结构标注.csv")
YAO_CSV = Path("/mnt/disk1/yanganqi/YJT/药典中药汇总.csv")
AGG_ROOT = Path("/mnt/disk1/yanganqi/YJT/data/原始数据汇总")
HERB2_SOURCE_BACKFILL_CSV = AGG_ROOT / "HERB2" / "HERB2_source_backfill_rows.csv"
QQCM_NAME_MAP = Path("/mnt/disk1/yanganqi/QQCM/id_trans/qqcm_pubchem_drugbank_mapping.tsv")
QQCM_SMILES = Path("/mnt/disk1/yanganqi/QQCM/COM/compound_smiles.csv")
QQCM_INCHIKEY = Path("/mnt/disk1/yanganqi/QQCM/COM/compound_inchikey.csv")
QQCM_HELPER_DIR = Path("/mnt/disk1/yanganqi/QQCM/KG/qqcm_compound_subgraph/helper_tables")
QQCM_MOL_GROUPS = QQCM_HELPER_DIR / "qqcm_compound_multi_mol_id_groups.tsv"
QQCM_CID_LOOKUP_DIR = Path("/mnt/disk1/yanganqi/QQCM/LLM/pubchem_cache/cid_lookup")
QQCM_TCMSP_CACHE_JSON = Path("/mnt/disk1/yanganqi/QQCM/COM/tcmsp_molecule_cache.json")

READ_ENCODINGS = ("utf-8-sig", "utf-8", "gb18030", "latin1")
FORMULA_COLUMNS = ("Molecular Formula", "MolecularFormula", "molecularformula", "Formula")
NAME_COLUMNS = ("Name", "name", "Queried Name", "Queried Identifier", "compound_name")
IUPAC_COLUMNS = ("IUPAC Name", "IUPACName", "iupacname")
SMILES_COLUMNS = ("SMILES", "CanonicalSMILES", "smiles", "SMILES.1")
INCHI_COLUMNS = ("InChI", "inchi")
INCHIKEY_COLUMNS = ("InChKey", "InChIKey", "inchikey")
CID_COLUMNS = ("PubChem CID", "pubchemcid", "CID", "cid", "mol_id")
CAS_COLUMNS = ("CAS", "cas")

SHORT_AMBIGUOUS = {
    "ado",
    "ann",
    "beo",
    "bzf",
    "cam",
    "cnh",
    "cpi",
    "cyt",
    "dbh",
    "dfv",
    "dhnq",
    "dle",
    "dmr",
    "dmt",
    "dob",
    "dtr",
    "dty",
    "dur",
    "eb",
    "ehbn",
    "eld",
    "esen",
    "fer",
    "foa",
    "fpr",
    "gbl",
    "gco",
    "gr",
    "gre",
    "gun",
    "hba",
    "hmf",
    "hmo",
    "iea",
    "ies",
    "ipmc",
    "l-",
    "ldp",
    "lof",
    "ltan",
    "mboa",
    "mhp",
    "mipk",
    "mlt",
    "mnn",
    "myf",
    "nfp",
    "nk",
    "noj",
    "ohp",
    "oxl",
    "pac",
    "pea",
    "pha",
    "phb",
    "pip",
    "ppy",
    "prz",
    "ptl",
    "pyc",
    "pyg",
    "rco",
    "rmn",
    "rng",
    "ron",
    "scg",
    "thz",
    "tml",
    "unal",
    "urc",
    "vca",
    "wv",
    "py",
}


def pick(row: dict[str, str], columns: tuple[str, ...]) -> str:
    for column in columns:
        value = row.get(column)
        if value is None:
            continue
        text = str(value).strip()
        if text and text.lower() != "nan":
            return text
    return ""


def norm_formula(value: str) -> str:
    return re.sub(r"\s+", "", value or "").upper()


def normalize_cid(value: str) -> str:
    text = (value or "").strip()
    if not text:
        return ""
    if text.upper().startswith("CID_") and text[4:].isdigit():
        return text[4:]
    if re.fullmatch(r"\d+\.0", text):
        return text[:-2]
    return text


def strip_accents(value: str) -> str:
    return "".join(
        ch for ch in unicodedata.normalize("NFKD", value) if not unicodedata.combining(ch)
    )


def normalize_name(value: str) -> str:
    text = (value or "").strip()
    if not text:
        return ""
    text = (
        text.replace("\u2019", "'")
        .replace("\u2018", "'")
        .replace("\u201c", '"')
        .replace("\u201d", '"')
        .replace("β", "beta")
        .replace("Β", "beta")
        .replace("α", "alpha")
        .replace("Α", "alpha")
        .replace("γ", "gamma")
        .replace("Γ", "gamma")
        .replace("δ", "delta")
        .replace("Δ", "delta")
        .replace("\u3000", " ")
    )
    text = strip_accents(text)
    text = re.sub(r"[_ ]+qt(?:\s*\d+)?$", "", text, flags=re.IGNORECASE)
    text = re.sub(r"\s+\d+$", "", text)
    text = text.strip(" ;,")
    text = re.sub(r"\s+", " ", text)
    return text.lower()


def clean_reference_name(value: str) -> str:
    text = (value or "").strip()
    if not text:
        return ""
    lowered = text.lower()
    for prefix in ("name:", "compound_name:", "compound name:"):
        if lowered.startswith(prefix):
            return text[len(prefix) :].strip()
    if lowered.startswith(("cid:", "smiles:", "inchikey:", "inchi:")):
        return ""
    return text


def alnum_name(value: str) -> str:
    return re.sub(r"[^a-z0-9]+", "", normalize_name(value))


def is_cas_name(value: str) -> bool:
    return bool(re.fullmatch(r"\d{2,7}-\d{2}-\d", value.strip()))


def is_inchi_literal(value: str) -> bool:
    return value.strip().startswith("InChI=")


def is_unresolved_noise(name: str) -> bool:
    n = normalize_name(name)
    if not n:
        return True
    if n in SHORT_AMBIGUOUS:
        return True
    if len(n) <= 2:
        return True
    if "_" in name:
        return True
    if re.fullmatch(r"[A-Z0-9\-]+", name) and len(name) <= 12:
        return True
    if "wln:" in n:
        return True
    if "pubchem cid" in n:
        return True
    return False


def open_csv_with_fallback(path: Path, delimiter: str = ","):
    raw = path.read_bytes()
    last_error = None
    for encoding in READ_ENCODINGS:
        try:
            text = raw.decode(encoding)
            handle = io.StringIO(text)
            reader = csv.DictReader(handle, delimiter=delimiter)
            if not reader.fieldnames:
                handle.close()
                continue
            return handle, reader
        except Exception as exc:  # pragma: no cover - filesystem/runtime dependent
            last_error = exc
    raise RuntimeError(f"Unable to read {path}") from last_error


def split_aliases(value: str) -> list[str]:
    aliases: list[str] = []
    for item in re.split(r"[;|]+", value or ""):
        cleaned = clean_reference_name(item)
        if cleaned:
            aliases.append(cleaned)
    return aliases


def load_group_cid_map() -> dict[str, str]:
    if not QQCM_MOL_GROUPS.exists():
        return {}
    mapping: dict[str, str] = {}
    with QQCM_MOL_GROUPS.open("r", encoding="utf-8-sig", newline="") as handle:
        reader = csv.DictReader(handle, delimiter="\t")
        for row in reader:
            mol_ids = [item.strip() for item in (row.get("mol_ids") or "").split("|") if item.strip()]
            cid_candidates = [item.removeprefix("CID_") for item in mol_ids if item.startswith("CID_")]
            if not cid_candidates:
                continue
            for mol_id in mol_ids:
                if mol_id.startswith("MOL") and mol_id not in mapping:
                    mapping[mol_id] = cid_candidates[0]
    return mapping


def load_lookup_cid_map() -> dict[str, str]:
    if not QQCM_CID_LOOKUP_DIR.exists():
        return {}
    mapping: dict[str, str] = {}
    for json_path in sorted(QQCM_CID_LOOKUP_DIR.glob("MOL*.json")):
        try:
            payload = json.loads(json_path.read_text(encoding="utf-8"))
        except Exception:
            continue
        candidates = payload.get("cid_candidates") or []
        if not candidates:
            continue
        cid_text = normalize_cid(str(candidates[0]))
        if cid_text and cid_text != "0":
            mapping[json_path.stem] = cid_text
    return mapping


def load_tcmsp_cache() -> dict[str, dict[str, object]]:
    if not QQCM_TCMSP_CACHE_JSON.exists():
        return {}
    try:
        return json.loads(QQCM_TCMSP_CACHE_JSON.read_text(encoding="utf-8"))
    except Exception:
        return {}


def resolve_qqcm_pubchem_cid(
    file_name: str,
    lookup_cids: dict[str, str],
    group_cids: dict[str, str],
    tcmsp_cache: dict[str, dict[str, object]],
) -> str:
    stem = file_name.rsplit(".", 1)[0] if "." in file_name else file_name
    if stem.startswith("CID_"):
        return normalize_cid(stem)
    if stem.startswith("MOL"):
        if stem in lookup_cids:
            return lookup_cids[stem]
        cached = tcmsp_cache.get(stem) or {}
        cached_cid = normalize_cid(str(cached.get("pubchem_cid") or ""))
        if cached_cid and cached_cid != "0":
            return cached_cid
        if stem in group_cids:
            return group_cids[stem]
    return normalize_cid(stem)


def structure_key(record: dict[str, str]) -> tuple[str, str]:
    for key in ("inchikey", "inchi", "smiles", "cid"):
        value = normalize_cid(record.get(key, "")) if key == "cid" else record.get(key, "").strip()
        if value:
            return key, value
    return "name_formula", f"{record.get('name', '')}|{record.get('formula', '')}"


def dedup_records(records: list[dict[str, str]]) -> list[dict[str, str]]:
    unique: list[dict[str, str]] = []
    for record in records:
        record = dict(record)
        record["cid"] = normalize_cid(record.get("cid", ""))

        merged = False
        for existing in unique:
            same_inchikey = (
                record.get("inchikey")
                and existing.get("inchikey")
                and record["inchikey"] == existing["inchikey"]
            )
            same_inchi = (
                record.get("inchi")
                and existing.get("inchi")
                and record["inchi"] == existing["inchi"]
            )
            same_smiles = (
                record.get("smiles")
                and existing.get("smiles")
                and record["smiles"] == existing["smiles"]
            )
            same_cid = record.get("cid") and existing.get("cid") and record["cid"] == existing["cid"]
            if same_inchikey or same_inchi or same_smiles or same_cid:
                for key, value in record.items():
                    if value and not existing.get(key):
                        existing[key] = value
                merged = True
                break

        if not merged:
            unique.append(record)
    return unique


def add_record(index: dict[str, defaultdict[str, list]], record: dict[str, str]) -> None:
    raw_names = {record.get("name", ""), record.get("iupac", "")}
    raw_names.update(record.get("aliases", []))
    for raw_name in raw_names:
        if not raw_name:
            continue
        cleaned_name = clean_reference_name(raw_name)
        if not cleaned_name:
            continue
        normalized = normalize_name(cleaned_name)
        if normalized:
            index["norm"][normalized].append(record)
        compact = alnum_name(cleaned_name)
        if compact:
            index["alnum"][compact].append(record)
    cas = record.get("cas", "").strip()
    if cas:
        index["cas"][cas].append(record)


def put_file_lookup(mapping: dict[str, str], file_name: str, value: str) -> None:
    if not file_name or not value:
        return
    mapping[file_name] = value
    stem = file_name
    if "." in file_name:
        stem = file_name.rsplit(".", 1)[0]
        mapping[stem] = value


def get_file_lookup(mapping: dict[str, str], file_name: str) -> str:
    if not file_name:
        return ""
    if file_name in mapping:
        return mapping[file_name]
    for suffix in (".sdf", ".mol2"):
        candidate = f"{file_name}{suffix}"
        if candidate in mapping:
            return mapping[candidate]
    stem = file_name.rsplit(".", 1)[0] if "." in file_name else file_name
    return mapping.get(stem, "")


def build_reference_index() -> dict[str, defaultdict[str, list]]:
    index: dict[str, defaultdict[str, list]] = {
        "norm": defaultdict(list),
        "alnum": defaultdict(list),
        "cas": defaultdict(list),
    }

    handle, reader = open_csv_with_fallback(YAO_CSV)
    try:
        for row in reader:
            record = {
                "source": "药典中药汇总",
                "name": clean_reference_name(pick(row, ("name",))),
                "iupac": pick(row, ("iupacname",)),
                "formula": pick(row, ("molecularformula",)),
                "smiles": pick(row, ("smiles",)),
                "inchi": pick(row, ("inchi",)),
                "inchikey": pick(row, ("inchikey",)),
                "cas": pick(row, ("cas",)),
                "cid": pick(row, ("pubchemcid",)),
                "aliases": [],
            }
            if record["name"] or record["iupac"]:
                add_record(index, record)
    finally:
        handle.close()

    for dirpath, _dirnames, filenames in os.walk(AGG_ROOT):
        for filename in filenames:
            if not filename.endswith("_Info_汇总.csv"):
                continue
            path = Path(dirpath) / filename
            handle, reader = open_csv_with_fallback(path)
            try:
                for row in reader:
                    record = {
                        "source": filename,
                        "name": clean_reference_name(pick(row, NAME_COLUMNS)),
                        "iupac": pick(row, IUPAC_COLUMNS),
                        "formula": pick(row, FORMULA_COLUMNS),
                        "smiles": pick(row, SMILES_COLUMNS),
                        "inchi": pick(row, INCHI_COLUMNS),
                        "inchikey": pick(row, INCHIKEY_COLUMNS),
                        "cas": pick(row, CAS_COLUMNS),
                        "cid": pick(row, CID_COLUMNS),
                        "aliases": [],
                    }
                    if record["name"] or record["iupac"]:
                        add_record(index, record)
            finally:
                handle.close()

    if HERB2_SOURCE_BACKFILL_CSV.exists():
        handle, reader = open_csv_with_fallback(HERB2_SOURCE_BACKFILL_CSV)
        try:
            for row in reader:
                if pick(row, ("sourcebackfillstatus",)) != "filled_ingredient_detail":
                    continue
                if not any(
                    pick(row, columns)
                    for columns in (
                        ("pubchemcid",),
                        ("smiles",),
                        ("inchi",),
                        ("inchkey",),
                        ("cas",),
                    )
                ):
                    continue
                queried_name = clean_reference_name(pick(row, ("queriedname",)))
                record = {
                    "source": "HERB2_source_backfill_rows",
                    "name": clean_reference_name(pick(row, ("sourceingredientname", "sourcepubchemname"))),
                    "iupac": pick(row, ("iupacname", "sourcepubchemname")),
                    "formula": pick(row, ("molecularformula",)),
                    "smiles": pick(row, ("smiles",)),
                    "inchi": pick(row, ("inchi",)),
                    "inchikey": pick(row, ("inchkey",)),
                    "cas": pick(row, ("cas",)),
                    "cid": pick(row, ("pubchemcid",)),
                    "aliases": (
                        split_aliases(pick(row, ("sourceingredientalias",)))
                        + ([queried_name] if queried_name else [])
                        + split_aliases(pick(row, ("sourcepubchemname",)))
                    ),
                }
                if record["name"] or record["iupac"] or record["aliases"]:
                    add_record(index, record)
        finally:
            handle.close()

    smiles_by_file: dict[str, str] = {}
    handle, reader = open_csv_with_fallback(QQCM_SMILES)
    try:
        for row in reader:
            smiles = pick(row, ("smiles",))
            file_name = pick(row, ("file_name",))
            put_file_lookup(smiles_by_file, file_name, smiles)
    finally:
        handle.close()

    inchikey_by_file: dict[str, str] = {}
    handle, reader = open_csv_with_fallback(QQCM_INCHIKEY)
    try:
        for row in reader:
            inchikey = pick(row, ("inchikey",))
            file_name = pick(row, ("file_name",))
            put_file_lookup(inchikey_by_file, file_name, inchikey)
    finally:
        handle.close()

    lookup_cids = load_lookup_cid_map()
    group_cids = load_group_cid_map()
    tcmsp_cache = load_tcmsp_cache()

    handle, reader = open_csv_with_fallback(QQCM_NAME_MAP, delimiter="\t")
    try:
        for row in reader:
            file_name = pick(row, ("file_name",))
            compound_name = clean_reference_name(pick(row, ("compound_name",)))
            if not file_name or not compound_name:
                continue
            record = {
                "source": "qqcm_pubchem_drugbank_mapping",
                "name": compound_name,
                "iupac": "",
                "formula": "",
                "smiles": get_file_lookup(smiles_by_file, file_name),
                "inchi": "",
                "inchikey": get_file_lookup(inchikey_by_file, file_name),
                "cas": "",
                "cid": resolve_qqcm_pubchem_cid(file_name, lookup_cids, group_cids, tcmsp_cache),
                "aliases": [],
            }
            add_record(index, record)
    finally:
        handle.close()

    return index


def match_records(
    name: str,
    formula: str,
    index: dict[str, defaultdict[str, list]],
) -> tuple[str, list[dict[str, str]], str]:
    if is_inchi_literal(name):
        return "无法解明结构", [], "名称字段是 InChI 文本,当前流程未解析 InChI 到标准标识符"

    if is_unresolved_noise(name):
        return "无法解明结构", [], "名称像缩写、内部代号、截断值或带噪声后缀,无法稳定对应唯一结构"

    candidates: list[dict[str, str]] = []
    reason = ""
    normalized = normalize_name(name)
    compact = alnum_name(name)

    if is_cas_name(name):
        candidates = dedup_records(index["cas"].get(name.strip(), []))
        reason = "按 CAS 号匹配本地参考库"
    else:
        candidates = dedup_records(index["norm"].get(normalized, []))
        if candidates:
            reason = "按标准化名称精确匹配本地参考库"
        elif compact:
            candidates = dedup_records(index["alnum"].get(compact, []))
            if candidates:
                reason = "按去符号名称匹配本地参考库"

    if not candidates:
        return "无法解明结构", [], "本地参考库未找到可用同名结构"

    matched_formula = [rec for rec in candidates if norm_formula(rec.get("formula", "")) == formula]
    if formula and len(matched_formula) == 1:
        return "唯一结构", matched_formula, f"{reason},且分子式唯一一致"
    if formula and len(matched_formula) > 1:
        return "多候选结构", matched_formula, f"{reason},但同名同分子式仍对应多个候选结构"

    if len(candidates) == 1:
        return "唯一结构", candidates, f"{reason},本地仅找到一个候选结构"

    return "多候选结构", candidates, f"{reason},同名对应多个候选结构"


def format_candidates(records: list[dict[str, str]], limit: int = 5) -> str:
    parts = []
    for record in records[:limit]:
        bits = []
        if record.get("name"):
            bits.append(record["name"])
        if record.get("formula"):
            bits.append(record["formula"])
        if record.get("cid"):
            bits.append(f"CID={record['cid']}")
        if record.get("inchikey"):
            bits.append(f"InChIKey={record['inchikey']}")
        parts.append(" | ".join(bits))
    return " ; ".join(parts)


def main() -> None:
    index = build_reference_index()
    status_counter: Counter[str] = Counter()

    with MS_CSV.open("r", encoding="utf-8-sig", newline="") as src, OUTPUT_CSV.open(
        "w", encoding="utf-8-sig", newline=""
    ) as dst:
        reader = csv.DictReader(src)
        fieldnames = list(reader.fieldnames or [])
        extra = [
            "structure_resolution",
            "matched_smiles",
            "matched_inchi",
            "matched_inchikey",
            "matched_pubchem_cid",
            "match_reason",
            "candidate_count",
            "candidate_examples",
        ]
        writer = csv.DictWriter(dst, fieldnames=fieldnames + extra)
        writer.writeheader()

        for row in reader:
            name = row.get("Name", "").strip()
            formula = norm_formula(row.get("Formula", ""))
            status, records, reason = match_records(name, formula, index)
            status_counter[status] += 1
            primary = records[0] if records else {}

            row.update(
                {
                    "structure_resolution": status,
                    "matched_smiles": primary.get("smiles", "") if status == "唯一结构" else "",
                    "matched_inchi": primary.get("inchi", "") if status == "唯一结构" else "",
                    "matched_inchikey": primary.get("inchikey", "") if status == "唯一结构" else "",
                    "matched_pubchem_cid": primary.get("cid", "") if status == "唯一结构" else "",
                    "match_reason": reason,
                    "candidate_count": str(len(records)),
                    "candidate_examples": format_candidates(records),
                }
            )
            writer.writerow(row)

    print(f"output={OUTPUT_CSV}")
    for status, count in sorted(status_counter.items()):
        print(f"{status}\t{count}")


if __name__ == "__main__":
    main()