#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""按当前语料库重算报告里每一条参考文献的 ✓全文/⚠摘要 标记，并从标记自动重建 §5 缺口表。
用法: python3 脚本/refresh_ref_flags.py
"""
import os, re, subprocess, sys

BASE = os.path.expanduser('~/Desktop/Hermes输出-工作类')
MD = os.path.join(BASE, '知识沉淀/蛋白突变改造_主流方案与迭代方向_20260912.md')
OA = os.path.join(BASE, '知识沉淀/_全文/OA')
norm = lambda s: re.sub(r'[^a-z0-9]', '', str(s).lower())
have = {norm(f[:-4]) for f in os.listdir(OA) if f.endswith('.txt')}
flag_of = lambda d: '✓全文' if norm(d) in have else '⚠摘要'

t = open(MD, encoding='utf-8').read()
refs = []
for line in t[t.find('## 7. 参考文献'):].split('\n'):
    m = re.search(r'DOI `([^`]+)`', line)
    if not (line.startswith('| ') and m):
        continue
    cells = [c.strip() for c in line.strip('|').split('|')]
    doi = m.group(1)
    title = re.sub(r'\.\s*DOI `.*$', '', cells[1]) if len(cells) > 1 else ''
    src = cells[2] if len(cells) > 2 else ''
    refs.append({'doi': doi, 'title': title, 'src': src, 'flag': flag_of(doi)})

# 1) 全文重算标记（正文内联引用 + §7 表格 + §4.x 表格）
n_flip = 0
for r in refs:
    pat = re.compile(r'(`%s`[^\n]{0,10}?)(?:✓全文|⚠摘要)' % re.escape(r['doi']))
    t, k = pat.subn(lambda m: m.group(1) + r['flag'], t)
    n_flip += k

# 2) 重建 §5 缺口表
miss = [r for r in refs if r['flag'] == '⚠摘要']
rows = ['| # | 文献 | DOI | 期刊 / 年 | 建议获取方式 |', '|---|---|---|---|---|']
for i, r in enumerate(miss, 1):
    rows.append('| %d | %s | `%s` | %s | 作者索取 → 馆际互借 → 单篇购买 |' % (i, r['title'], r['doi'], r['src']))
head = ('## 5. 文献缺口（已核实存在、但本机未获全文者）\n\n'
        '> 下表由 `脚本/refresh_ref_flags.py` 按本机语料库自动生成，共 **%d 条**。每条 DOI 均经 Crossref/Europe PMC 核实**真实存在**；'
        '缺口原因是出版社付费墙或本机无法访问，**不影响其作为引用来源**，但涉及具体数值时本报告一律不转抄未读到的数字。\n\n'
        % len(miss))
new5 = head + '\n'.join(rows) + '\n\n---\n\n'
i5, i6 = t.find('## 5. 文献缺口'), t.find('## 6.')
assert i5 > 0 and i6 > i5
t = t[:i5] + new5 + t[i6:]

open(MD, 'w', encoding='utf-8').write(t)
print('标记重算：改写 %d 处' % n_flip)
print('参考文献 %d ｜ ✓全文 %d ｜ ⚠摘要（=缺口表） %d' % (len(refs), len(refs) - len(miss), len(miss)))
r = subprocess.run(['/usr/bin/python3', os.path.join(BASE, '脚本/build_protein_report.py')],
                   capture_output=True, text=True, timeout=300)
print(r.stdout.strip() or r.stderr.strip()[:300])
print('\n仍缺口清单:')
for i, m in enumerate(miss, 1):
    print('  %2d. %s | %s | %s' % (i, m['title'][:78], m['src'][:38], m['doi']))
