# -*- coding: utf-8 -*-
import re,json,os,sys
sys.path.insert(0,".")
import verify_grok as vg

MD="审核/整改2/AB卷-定稿2.12完整版.md"
t=open(MD,encoding="utf-8").read()
PAGES=dict(vg.PAGES)
# 补第2章原始全书 OCR
ch2="/home/zyw/Downloads/dl-hub/23-拍照OCR取字/data/books/软件项目管理与实践_第2章_软件项目启动_第15-32页/全书_纯净全文_20260923_203259.txt"
if os.path.exists(ch2):
    for m in re.finditer(r"第\s*(\d+)\s*页",open(ch2,encoding="utf-8").read()[:0]): pass
def load_ch2_pages():
    txt=open(ch2,encoding="utf-8").read() if os.path.exists(ch2) else ""
    return txt
CH2=load_ch2_pages()

def paper(seg):
    q=seg[seg.find("## 试题"):seg.find("## 参考答案")]
    a=seg[seg.find("## 参考答案"):]
    return q,a

def sections(text):
    out=[];cur=None
    for ln in text.split("\n"):
        if ln.startswith("### "):
            cur=[ln[4:].strip(),[]]; out.append(cur)
        elif cur is not None:
            cur[1].append(ln)
    return out

def items(lines):
    out=[];cur=None
    for ln in lines:
        m=re.match(r"\*\*(\d+)\.\*\*",ln)
        if m:
            cur=[m.group(1),[ln[m.end():].strip()]]; out.append(cur)
        elif cur is not None:
            cur[1].append(ln)
    return out

def clean(lines):
    res=[]
    for ln in lines:
        s=ln.rstrip()
        if not s.strip(): continue
        res.append(s)
    return res

def quote_for(pages, kws):
    texts=[(p,PAGES[p]) for p in pages if p in PAGES]
    if CH2: texts.append(("ch2",CH2))
    for p,txt in texts:
        for kw in kws:
            if len(kw)<2: continue
            i=txt.find(kw)
            if i<0: continue
            s=max(txt.rfind("。",0,i),txt.rfind("\n",0,i))+1
            e=txt.find("。",i)
            seg=txt[s:e+1 if e>0 else len(txt)].strip().replace("\n"," ")
            seg=re.sub(r"^#+\s*","",seg)
            seg=re.sub(r"^\d+(\.\d+)*\s+\S{2,14}\s+","",seg)
            seg=re.sub(r"^\d+(\.\d+)*\s*[\u4e00-\u9fa5A-Za-z、（）()]{0,20}\s*","",seg)
            seg=re.sub(r"\*\*|>\s*","",seg).strip()
            if 10<=len(seg)<=160:
                return p,seg
    # 回退：全书检索关键词
    for kw in kws:
        if len(kw)<2: continue
        for p,txt in list(PAGES.items())+([("ch2",CH2)] if CH2 else []):
            i=txt.find(kw)
            if i<0: continue
            s0=max(txt.rfind("。",0,i),txt.rfind("\n",0,i))+1
            e=txt.find("。",i)
            seg=txt[s0:e+1 if e>0 else len(txt)].strip().replace("\n"," ")
            seg=re.sub(r"^#+\s*","",seg); seg=re.sub(r"\*\*|>\s*","",seg).strip()
            seg=re.sub(r"^\d+(\.\d+)*\s+\S{2,14}\s+","",seg)
            seg=re.sub(r"^\d+(\.\d+)*\s*[\u4e00-\u9fa5A-Za-z、（）()]{0,20}\s*","",seg)
            if 10<=len(seg)<=160: return p,seg
    return None,None

def build(seg,label,out):
    q,a=paper(seg)
    def norm(x): return x.split("（")[0].strip()
    qs={norm(s[0]):(s[0],s[1]) for s in sections(q)}
    as_={norm(s[0]):s[1] for s in sections(a)}
    L=[f"# {label} 卷逐题解析报告",""]
    for title in qs:
        full,qlines_all=qs[title]
        L.append(f"## {full}"); L.append("")
        qitems=items(qlines_all)
        aitems=items(as_.get(title,[]))
        amap={x[0]:clean(x[1]) for x in aitems}
        optmap={}
        for ln in qlines_all if isinstance(qlines_all,list) else []:
            pass
        for no,qlines in qitems:
            L.append(f"### {title.split('（')[0]} 第 {no} 题"); L.append("")
            L.append("**原题**"); L.append("")
            for ln in clean(qlines): L.append(ln)
            L.append("")
            al=amap.get(no,[])
            ans=next((x for x in al if x.startswith("答案：")),None) or next((x for x in al if x.startswith("答：")),None)
            expl=next((x for x in al if x.startswith("解析：")),None)
            kp=next((x for x in al if x.startswith("知识点：")),None)
            pages=re.findall(r"P(\d+)",(ans or "")+" "+" ".join(al))
            pages=[int(x) for x in pages]
            kws=[]
            for ln in qlines:
                m2=re.match(r"^([A-D])[\.、]\s*(.+)",ln.strip())
                if m2: optmap[m2.group(1)]=m2.group(2)
            if ans:
                mm=re.search(r"答案：([A-D])",ans)
                if mm and mm.group(1) in optmap: kws.append(optmap[mm.group(1)])
            if ans and not re.search(r"答案：([A-D])",ans):
                body=re.sub(r"^(答案|答)：","",ans); body=re.sub(r"（教材.*$","",body)
                kws+= [x for x in re.split(r"[（(]\d[)）]|[；;、。，,：:\s]+",body) if len(x)>=2]
            if kp: kws+=re.split(r"[；;、，,：:\s]",kp.split("：",1)[-1])
            if ans:
                body=re.sub(r"^(答案|答)：","",ans); body=re.sub(r"（教材.*$","",body)
                kws=[re.sub(r"^[A-D][\.、]","",body).strip()]+kws
            kws=[k for k in kws if len(k)>=2]
            p,quote=quote_for(pages,kws)
            L.append(f"**答案**：{(ans or '').replace('答案：','')}"); L.append("")
            if expl: L.append(f"**解析**：{expl.replace('解析：','')}"); L.append("")
            seen=[]; [seen.append(x) for x in pages if x not in seen]
            L.append(f"**教材出处**：{'、'.join('P'+str(x) for x in seen) if seen else '未标注'}")
            L.append("")
            if quote: L.append(f"**教材原文**：{quote}"); L.append("")
            else: L.append("**教材原文**：该页未检索到与答案直接对应的原句，解析已按相关页表述撰写，建议人工复核。"); L.append("")
            L.append("---"); L.append("")
    open(out,"w",encoding="utf-8").write("\n".join(L)); print("saved",out)

A=t[t.find("# A 卷"):t.find("# B 卷")]
B=t[t.find("# B 卷"):t.find("# 本次自查统计")]
os.makedirs("定稿输出",exist_ok=True)
build(A,"A","定稿输出/A卷逐题解析报告.md")
build(B,"B","定稿输出/B卷逐题解析报告.md")
