#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""每日学习报告 → 企微群机器人。用法：python3 push_report.py [YYYY-MM-DD]"""
import json, os, sys, urllib.request, datetime

ROOT = "/Users/zhangwen/.local/share/TeleAgent/TeleAgent的工作空间/学习工作台"
REPORT_DIR = ROOT + "/reports"
WEBHOOK = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b42a6075-e686-4948-9ef6-f2365ef727d3"

def today():
    return datetime.date.today().isoformat()

def load(date):
    p = os.path.join(REPORT_DIR, date + ".json")
    if not os.path.exists(p):
        return {"date": date, "subjects": {}}
    try:
        with open(p, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception:
        return {"date": date, "subjects": {}}

def build_message(rep):
    d = rep.get("date", today())
    subs = rep.get("subjects") or {}
    lines = []
    lines.append(f"【芯芯学习 · {d}】")

    en = subs.get("en") or {}
    if en:
        read = en.get("read", 0)
        follow = en.get("follow", {})
        spell = en.get("spell", {})
        recite = en.get("recite", {})
        ftot = en.get("totals", {}).get("follow") or max(len(follow), 1)
        stot = en.get("totals", {}).get("spell") or max(len(spell), 1)
        rtot = en.get("totals", {}).get("recite") or max(len(recite), 1)
        fdone = sum(1 for v in follow.values() if v is not None)
        sdone = sum(1 for v in spell.values() if v is not None)
        rdone = sum(1 for v in recite.values() if v is not None)
        favg = int(sum(follow.values()) / len(follow)) if follow and any(v is not None for v in follow.values()) else 0
        savg = int(sum(spell.values()) / len(spell)) if spell and any(v is not None for v in spell.values()) else 0
        ravg = int(sum(recite.values()) / len(recite)) if recite and any(v is not None for v in recite.values()) else 0
        lines.append(f"📗 英语：跟读 {fdone}/{ftot} · 听写 {sdone}/{stot} · 背诵 {rdone}/{rtot}")
        lines.append(f"　　正确率：跟读{favg}% · 听写{savg}% · 背诵{ravg}%")
    else:
        lines.append("📗 英语：今天还没学习")

    yu = subs.get("yu") or {}
    if yu:
        done = yu.get("done") or {}
        names = {"zishi":"识字写字","woci":"词语积累","beisong":"背诵默写","kewen":"课文要点","juzi":"句子·写话"}
        done_names = [names[k] for k in names if done.get(k)]
        yu_total = yu.get("total") or 5
        lines.append(f"📖 语文：完成 {len(done_names)}/{yu_total} → " + ("、".join(done_names) if done_names else "尚未打卡"))
    else:
        lines.append("📖 语文：今天未学习")

    sh = subs.get("sh") or {}
    if sh:
        done = sh.get("done") or {}
        names = {"kf":"乘法口诀","chufa":"表内除法","changdu":"厘米和米","fenlei":"分类方向","kousuan":"口算"}
        done_names = [names[k] for k in names if done.get(k)]  # 输出中文板块名
        ks = sh.get("ksBest")
        ks_str = f"，口算最佳 {ks}%" if ks is not None else ""
        sh_total = sh.get("total") or 5
        lines.append(f"📙 数学：拿下 {len(done_names)}/{sh_total} → " + ("、".join(done_names) if done_names else "尚未打卡") + ks_str)
    else:
        lines.append("📙 数学：今天未学习")

    # 汇总
    n_subj = sum(1 for k in ("en","yu","sh") if subs.get(k))
    lines.append(f"\n今日共学习 {n_subj}/3 科，坚持就是胜利！🎉")
    return "\n".join(lines)

def send(text):
    body = {"msgtype": "text", "text": {"content": text}}
    req = urllib.request.Request(WEBHOOK, data=json.dumps(body).encode("utf-8"),
                                 headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=15) as r:
        resp = json.loads(r.read().decode("utf-8"))
    if resp.get("errcode") != 0:
        raise RuntimeError("webhook error: " + json.dumps(resp, ensure_ascii=False))
    return resp

def _mark_file(date):
    return os.path.join(REPORT_DIR, date + ".pushed")

def already_pushed(date):
    return os.path.exists(_mark_file(date))

def mark_pushed(date):
    try:
        os.makedirs(REPORT_DIR, exist_ok=True)
        with open(_mark_file(date), "w", encoding="utf-8") as f:
            f.write(datetime.datetime.now().isoformat())
    except Exception:
        pass

if __name__ == "__main__":
    args = sys.argv[1:]
    if "--yesterday" in args:
        args = [a for a in args if a != "--yesterday"]
        date = (datetime.date.today() - datetime.timedelta(days=1)).isoformat()
    elif args and not args[0].startswith("--"):
        date = args[0]
        args = args[1:]
    else:
        date = today()
    if "--force" not in args and already_pushed(date):
        print(f"（{date}）已推送过，跳过（避免重复）。如需重推请加 --force")
        sys.exit(0)
    rep = load(date)
    subs = rep.get("subjects") or {}
    has_data = any(bool(v) for v in subs.values())
    if not has_data and "--force" not in args:
        print(f"（{date}）无学习数据，跳过推送")
        sys.exit(0)
    msg = build_message(rep)
    print("=== 推送内容 ===")
    print(msg)
    if "--dry" in args:
        print("（dry-run，未实际发送，不标记已推送）")
    else:
        r = send(msg)
        mark_pushed(date)
        print("已发送成功:", r)