import re,sys
h=open('ngspice_manual.html').read()
def div_end(s,j):
    depth=0;k=j
    while k<len(s):
        nd=s.find('<div',k);ndc=s.find('</div>',k)
        if ndc<0:return len(s)
        if nd!=-1 and nd<ndc:depth+=1;k=nd+4
        else:
            depth-=1;k=ndc+6
            if depth==0:return k
    return len(s)
ref_start=h.index('<h2 id="reference"');osdi_start=h.index('<h2 id="osdi"')
first_cmd=h.index('<div class="cmd">',ref_start)
ref_intro=h[ref_start:first_cmd];ref_body=h[first_cmd:osdi_start]
blocks=[];i=0
while True:
    j=ref_body.find('<div class="cmd">',i)
    if j<0:break
    e=div_end(ref_body,j);block=ref_body[j:e]
    blocks.append((re.search(r'<h3 id="([^"]+)"',block).group(1),block));i=e
blocks.sort(key=lambda x:x[0])
def li(cid,block):
    h3=re.sub(r'<span class="mode.*','',re.search(r'<h3[^>]*>(.*?)</h3>',block,re.S).group(1),flags=re.S)
    codes,_,desc=h3.partition('—')
    codes=re.sub(r'<code>\.',r'<code><span class="dot">.</span>',codes).strip()
    desc=re.sub(r'<[^>]+>','',desc).strip()
    if cid=='step':return '<li class="todo"><a href="#step"><code><span class="dot">.</span>step</code></a> — not supported (use a loop)</li>'
    return f'<li><a href="#{cid}">{codes}</a>'+(f' — {desc}</li>' if desc else '</li>')
idx='\n'.join(li(c,b) for c,b in blocks)+'\n<li><a href="#osdi"><code>osdi</code></a> — compiled foundry passives</li>'
new=h[:ref_start]+ref_intro+'\n'.join(b for _,b in blocks)+'\n\n'+h[osdi_start:]
new=re.sub(r'(<nav class="alpha">.*?<ul>).*?(\s*</ul>)', lambda m:m.group(1)+'\n'+idx+'\n</ul>', new, flags=re.S)
open('ngspice_manual.html','w').write(new)
bad=[t for t in ['div','figure','pre','h2','h3','ul','ol','li'] if len(re.findall(r'<%s[ >]'%t,new))!=len(re.findall(r'</%s>'%t,new))]
ids=re.findall(r'id="([^"]+)"',new);dup=[i for i in set(ids) if ids.count(i)>1]
anc=set(re.findall(r'href="#([^"]+)"',new));miss=[a for a in anc if a not in set(ids)]
print("tags",("OK" if not bad else bad),"| dup",dup or "none","| broken",miss or "none","| ref entries",len(blocks))
