"""Check structural scientific data, references, links, and localization substitutions."""
from pathlib import Path
import re,json,yaml
r=Path(__file__).resolve().parents[1]
issues=[]
def check(ok,detail):
 if not ok:issues.append(detail)
def data(path):return yaml.safe_load(path.read_text().split('---',2)[1])
def body(path):return path.read_text().split('---',2)[2]
articles=list((r/'content/en').rglob('*.mdx'))
for src in articles:
 dst=r/'content/fa'/src.relative_to(r/'content/en')
 check(dst.exists(),str(dst))
 if not dst.exists():continue
 a,b=data(src),data(dst);aa,bb=body(src),body(dst)
 for key in a.keys()-{'title','description','aliases'}:check(a[key]==b.get(key),f'{src.stem}: metadata {key}')
 cites=lambda s:re.findall(r'<Cite\s+n=\{(.*?)\}\s*/>',s,re.S)
 check(cites(aa)==cites(bb),f'{src.stem}: citation sequence')
 components=lambda s:re.findall(r'<(?:HeartModel|EcgMonitor|Quiz)\b[\s\S]*?/?>',s)
 check(components(aa)==components(bb),f'{src.stem}: model/quiz attributes')
 links=lambda s:re.findall(r'\]\(([^)]+)\)',s)
 check(sorted(links(aa))==sorted(links(bb)),f'{src.stem}: link destinations')
 for marker in ['Patient','Student']:check(len(re.findall('<'+marker+'>',aa))==len(re.findall('<'+marker+'>',bb)),f'{src.stem}: {marker} blocks')
 check(not re.search(r'X\d+X|⁇',bb),f'{src.stem}: translation placeholder')
 check(re.search('[\u0600-\u06ff]',b['title']),f'{src.stem}: Persian title')
quizzes=list((r/'content/en').rglob('*.quiz.yaml'))
for src in quizzes:
 dst=r/'content/fa'/src.relative_to(r/'content/en');a,b=yaml.safe_load(src.read_text()),yaml.safe_load(dst.read_text())
 for x,y in zip(a['questions'],b['questions'],strict=True):
  for k in x.keys()-{'prompt','explanation','options'}:check(x[k]==y[k],f'{src.stem}: quiz {k}')
  for u,v in zip(x['options'],y['options'],strict=True):check({k:w for k,w in u.items() if k!='text'}=={k:w for k,w in v.items() if k!='text'},f'{src.stem}: correct answer')
en=json.loads((r/'apps/web/src/i18n/messages/en.json').read_text());fa=json.loads((r/'apps/web/src/i18n/messages/fa.json').read_text())
check(en.keys()==fa.keys(),'UI key set')
for k,v in en.items():
 if ', plural,' in v:continue
 placeholders=lambda s:sorted(re.findall(r'\{\w+\}|\[(?:COUNT|SEARCH_TERM|DIFFERENT_TERM)\]',s))
 check(placeholders(v)==placeholders(fa[k]),f'UI substitution {k}')
check(not issues,'No structural issues')
report={'articles':len(articles),'quizzes':len(quizzes),'ui_keys':len(en),'structural_issues':issues}
(r/'docs/persian-content-check.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
if issues:
 print('\n'.join(issues));raise SystemExit(1)
print(json.dumps(report,ensure_ascii=False))
