import json,sys,os,re
from collections import defaultdict,Counter
ROOT='/Users/jaganat/git_projects/vedabase-original'
SYN=re.compile(r'\*[^*\n]+\*\s*—')
def ref_of(fname):
    stem=os.path.basename(fname).replace('.md','')
    m=re.match(r'cc-(adi|madhya|antya)-(\d+)\.(\d+[a-z]?(?:-\d+)?)$',stem)
    if m: return f"cc/{m.group(1)}/{m.group(2)}/{m.group(3)}"
    m=re.match(r'sb-(\d+)\.(\d+)\.(\d+.*)$',stem)
    if m: return f"sb/{m.group(1)}/{m.group(2)}/{m.group(3)}"
    return stem
def apply_conf(conf, note):
    byf=defaultdict(list)
    for v in conf: byf[v['file']].append(v)
    applied=[]; skipped=[]; corr=[]
    for f,fixes in byf.items():
        p=os.path.join(ROOT,f)
        if not os.path.exists(p): continue
        lines=open(p,encoding='utf-8').read().split('\n')
        for v in fixes:
            o,n=v['fix_old'],v['fix_new']
            if o==n: continue
            whole='\n'.join(lines)
            if whole.count(o)==1:
                lines=whole.replace(o,n,1).split('\n'); applied.append(v); corr.append((f,o,n))
            else:
                syn=[i for i,ln in enumerate(lines) if len(SYN.findall(ln))>=2 and o in ln]
                tot=sum(lines[i].count(o) for i in syn)
                if tot==1:
                    i=syn[0]; lines[i]=lines[i].replace(o,n,1); applied.append(v); corr.append((f,o,n))
                else:
                    skipped.append((os.path.basename(f),o,f"{whole.count(o)}x/{tot}syn"))
        open(p,'w',encoding='utf-8').write('\n'.join(lines))
    with open(os.path.join(ROOT,"corrections.jsonl"),"a",encoding="utf-8") as fh:
        for f,o,n in corr:
            fh.write(json.dumps({"ref":ref_of(f),"field":"synonyms","file":f,
                     "replace":{"en":[o.replace('*',''),n.replace('*','')]},
                     "note":note,"applied_d1":False,"date":"2026-07-27"},ensure_ascii=False)+"\n")
    return applied, skipped
