#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""内容质检：CPM / EVM 复算、答案分布、选项重复、填空题空数、答案文本一致性"""
import re, json, sys
from collections import Counter

def cpm(acts):
    ids = [a["id"] for a in acts]
    dur = {a["id"]: a["dur"] for a in acts}
    pred = {a["id"]: a.get("pred", []) or [] for a in acts}
    succ = {i: [] for i in ids}
    for a in acts:
        for p in pred[a["id"]]:
            succ[p].append(a["id"])
    # topo
    indeg = {i: len(pred[i]) for i in ids}
    q = [i for i in ids if indeg[i] == 0]
    order = []
    while q:
        n = q.pop(0); order.append(n)
        for s in succ[n]:
            indeg[s] -= 1
            if indeg[s] == 0:
                q.append(s)
    if len(order) != len(ids):
        raise ValueError("网络图存在环")
    ES, EF = {}, {}
    for i in order:
        ES[i] = max([EF[p] for p in pred[i]], default=0)
        EF[i] = ES[i] + dur[i]
    total = max(EF.values())
    LF, LS = {}, {}
    for i in reversed(order):
        LF[i] = min([LS[s] for s in succ[i]], default=total)
        LS[i] = LF[i] - dur[i]
    TF = {i: LS[i] - ES[i] for i in ids}
    FF = {}
    for i in ids:
        FF[i] = min([ES[s] for s in succ[i]], default=total) - EF[i]
    crit = [i for i in ids if TF[i] == 0]
    # one critical path (follow TF=0 successors)
    starts = [i for i in ids if TF[i] == 0 and not any(pred[i])]
    paths = []
    def dfs(n, path):
        if not succ[n] or not any(TF[s] == 0 for s in succ[n]):
            paths.append(path[:]); return
        for s in succ[n]:
            if TF[s] == 0:
                dfs(s, path + [s])
    for s in starts:
        dfs(s, [s])
    return {"dur": total, "ES": ES, "EF": EF, "LS": LS, "LF": LF, "TF": TF, "FF": FF,
            "crit": crit, "paths": paths}


def evm(dc):
    p = dc["check_period"]
    idx = dc["periods"].index(p) if p in dc["periods"] else len(dc["periods"]) - 1
    PV, EV, AC = dc["PV"][idx], dc["EV"][idx], dc["AC"][idx]
    BAC = dc["BAC"]
    out = {"PV": PV, "EV": EV, "AC": AC,
           "CV": EV - AC, "SV": EV - PV,
           "CPI": EV / AC if AC else None, "SPI": EV / PV if PV else None}
    if out["CPI"]:
        out["EAC_typical"] = BAC / out["CPI"]
        out["ETC_typical"] = out["EAC_typical"] - AC
        out["VAC_typical"] = BAC - out["EAC_typical"]
    out["EAC_atypical"] = AC + (BAC - EV)
    out["ETC_atypical"] = out["EAC_atypical"] - AC
    out["TCPI"] = (BAC - EV) / (BAC - AC) if BAC != AC else None
    return out


def nums(s):
    s = (s or "").replace("\u2212", "-").replace("－", "-").replace("–", "-")
    return [float(x) for x in re.findall(r"-?\d+(?:\.\d+)?", s)]


def appears(val, text, tol=0.02):
    if val is None:
        return True
    for n in nums(text):
        if abs(n - val) <= max(tol, abs(val) * 0.005):
            return True
    return False


def qa(papers):
    issues = []
    for pid, items in papers.items():
        sgl = [i for i in items if i["type"] == "single"]
        tf = [i for i in items if i["type"] == "tf"]
        ans = Counter(i["answer"] for i in sgl)
        if max(ans.values()) - min(ans.values()) > 3:
            issues.append(f"{pid}: 单选答案分布不均 {dict(ans)}")
        for i in sgl:
            if len(set(i["options"])) != 4:
                issues.append(f"{pid}/{i['slot']}: 选项重复")
            letters = [o.strip()[:1] for o in i["options"]]
            if letters != list("ABCD"):
                issues.append(f"{pid}/{i['slot']}: 选项前缀不是A-D")
        tfa = Counter(i["answer"] for i in tf)
        tfx = tfa.get("×", 0) + tfa.get("错", 0)
        tfd = tfa.get("√", 0) + tfa.get("对", 0)
        if tfx != 5 or tfd != 5:
            issues.append(f"{pid}: 判断√/× = {tfd}/{tfx}（应为5/5）")
        for i in items:
            if i["type"] == "fill":
                if len(i["answers"]) != 2 or i["stem"].count("______") != 2:
                    issues.append(f"{pid}/{i['slot']}: 填空空数异常")
                if any(not a.strip() for a in i["answers"]):
                    issues.append(f"{pid}/{i['slot']}: 填空答案为空")
        # C2 / C3 复算
        for i in items:
            dc = i.get("data_check") or {}
            if dc.get("type") == "cpm":
                try:
                    r = cpm(dc["activities"])
                except Exception as e:
                    issues.append(f"{pid}/{i['slot']}: CPM 数据错误 {e}")
                    continue
                ans = i.get("answer", "")
                if not appears(r["dur"], ans):
                    issues.append(f"{pid}/{i['slot']}: 答案未出现总工期 {r['dur']}")
                if r["paths"]:
                    cp = "→".join(r["paths"][0])
                    if not any(ch in ans for ch in cp.split("→")[:2]):
                        issues.append(f"{pid}/{i['slot']}: 答案未出现关键路径 {cp}")
                i["_cpm"] = r
            if dc.get("type") == "evm":
                r = evm(dc)
                ans = i.get("answer", "")
                for k in ["CPI", "SPI", "CV", "SV"]:
                    if r.get(k) is not None and not appears(round(r[k], 2), ans, 0.05):
                        issues.append(f"{pid}/{i['slot']}: 答案未出现 {k}={r[k]:.2f}")
                if not appears(round(r["EAC_typical"], 2), ans, 0.1):
                    issues.append(f"{pid}/{i['slot']}: 答案未出现 EAC(典型)={r['EAC_typical']:.2f}")
                i["_evm"] = r
    return issues


if __name__ == "__main__":
    sys.path.insert(0, "/home/zyw/Downloads/dl-hub/22-软件项目管理教学包/命题-2026秋/工作区")
    import build_papers as bp
    a, c = bp.load_all()
    P = bp.assemble(a, c)
    iss = qa(P)
    print(f"{len(iss)} issues")
    for x in iss[:100]:
        print(" -", x)
