"""python/peps -> ctx decision records. Frontmatter only from the PEP's own text: header fields, and
the summary is the first paragraph of the author's Abstract (Title when there is none). Nothing generated."""
import sys,re,json,pathlib
src,out=map(pathlib.Path,sys.argv[1:3]); out.mkdir(parents=True,exist_ok=True)
CUR={'final':'accepted','accepted':'accepted','active':'accepted','draft':'proposed','provisional':'proposed'}
stats={'n':0,'title_fallback':0}
q=lambda s: json.dumps(s)
for f in sorted(src.glob('pep-*.rst')):
    text=f.read_text(encoding='utf-8',errors='replace'); head,_,body=text.partition('\n\n')
    h={};k=None
    for line in head.splitlines():
        if re.match(r'^\S[^:]*:',line): k,v=line.split(':',1); h[k.strip()]=v.strip()
        elif k: h[k]+=' '+line.strip()
    if 'PEP' not in h: continue
    n=int(h['PEP']); pid=f'pep-{n:04d}'
    m=re.search(r'^Abstract\n=+\n+(.+?)(\n\n|\Z)',body,re.S|re.M)
    summ=' '.join(m.group(1).split()) if m else None
    if not summ: summ=h.get('Title',''); stats['title_fallback']+=1
    st=h.get('Status','').lower(); status=CUR.get(st,st or 'unknown')
    ids=lambda key: [f'pep-{int(x):04d}' for x in re.findall(r'\d+',h.get(key,''))]
    fm=['---',f'id: {pid}',f'title: {q("PEP "+str(n)+": "+h.get("Title",""))}',f'summary: {q(summ)}',
        f'tags: {q([h.get("Type",""), h.get("Status","")])}',f'status: {status}']
    if ids('Replaces'): fm.append(f'supersedes: {q(ids("Replaces"))}')
    if ids('Superseded-By'): fm.append(f'superseded-by: {q(ids("Superseded-By"))}')
    fm.append('---')
    (out/f'{pid}.md').write_text('\n'.join(fm)+'\n\n'+text,encoding='utf-8'); stats['n']+=1
print(stats)
