# -*- coding: utf-8 -*-
import json, io, os, sys, openpyxl
import _remerge
ROOT=r"D:\01.프로젝트\DB수집"
d=json.load(io.open(os.path.join(ROOT,"작업파일","_targets.json"),encoding="utf-8"))
which=sys.argv[1] if len(sys.argv)>1 else "work"
files=d[which]
out=io.open(os.path.join(ROOT,"작업파일","_remerge_report_%s.txt"%which),"w",encoding="utf-8")
def w(*a): out.write(" ".join(str(x) for x in a)+"\n"); 
done=skip=fail=changed=0
for rel in files:
    p=os.path.join(ROOT,rel)
    if "test" in os.path.basename(p).lower():
        w("SKIP(test)",rel); skip+=1; continue
    # KDHC already done
    if "지역난방" in rel:
        w("SKIP(KDHC done)",rel); skip+=1; continue
    try:
        wb=openpyxl.load_workbook(p); ws=wb.active; mc=ws.max_column; mr=ws.max_row; wb.close()
    except Exception as e:
        w("LOADERR",rel,e); fail+=1; continue
    if mc<20 or mr<3:
        w("SKIP(not collection mc=%d mr=%d)"%(mc,mr),rel); skip+=1; continue
    try:
        r=_remerge.process(p, apply=True, height=False)
    except Exception as e:
        w("EXC",rel,repr(e)); fail+=1; continue
    if not r.get("ok"):
        w("FAIL",rel,"rolledback=%s fails=%s"%(r.get("rolledback"),r.get("fails"))); fail+=1; continue
    nc=r.get("n_change",0); orp=len(r.get("orphans",[]))
    if r.get("nochange"):
        w("OK-nochange",rel); done+=1
    else:
        w("OK changes=%d orphans=%d merges=%s"%(nc,orp,r.get("n_merges_after")),rel,
          "| add="+str(r.get("add"))[:200])
        done+=1; 
        if nc>0 or orp>0: changed+=1
out.write("\n=== SUMMARY %s: done=%d changed=%d skip=%d fail=%d (total %d) ===\n"%(which,done,changed,skip,fail,len(files)))
out.close()
print("%s done=%d changed=%d skip=%d fail=%d total=%d"%(which,done,changed,skip,fail,len(files)))
