#!/usr/bin/env python3
"""发送今日课程提醒卡片给所有学员（今日 19:30 开营仪式）"""
import json, time, subprocess, sys

NOTIFY_FILE = "/home/ubuntu/.openclaw/workspace/projects/openclaw-cn-tutorial/courses/social-layer/dm-activity/notifications/2026-03-21.json"
MEMBER_FILE = "/home/ubuntu/.openclaw/workspace/projects/openclaw-cn-tutorial/courses/social-layer/students/member-mapping.json"
STAMP_DIR   = "/home/ubuntu/.openclaw/workspace/projects/openclaw-cn-tutorial/courses/social-layer/dm-activity/stamps/2026-03-21"

with open(NOTIFY_FILE) as f:
    notify = json.load(f)

with open(MEMBER_FILE) as f:
    mapping = json.load(f)

course = notify["courses_matched"][0]
m, d = notify["m"], notify["d"]

card = {
    "msg_type": "interactive",
    "card": {
        "header": {
            "title": {"tag": "plain_text", "content": f"🦞 OpenClaw 共学营｜今晚课程提醒（{m}月{d}日）"},
            "template": "purple"
        },
        "elements": [
            {
                "tag": "div",
                "text": {
                    "tag": "lark_md",
                    "content": (
                        f"**📅 日期：** {course['日期']}\n"
                        f"**⏰ 时间：** {course['开始和结束时间']}\n"
                        f"**👨‍🏫 讲师：** {course['讲师']}\n\n"
                        f"**📖 课程内容：**\n{course['课程内容'].replace(chr(10), chr(10)+' ')}"
                    )
                }
            },
            {"tag": "hr"},
            {
                "tag": "action",
                "actions": [
                    {
                        "tag": "button",
                        "text": {"tag": "plain_text", "content": "📋 打开课程表"},
                        "type": "primary",
                        "url": "https://ocnvstmj9top.feishu.cn/wiki/L8KGwKSDWiFOWXklJukcTB8jnSe?table=tblVCt3IR6bcTGCR"
                    }
                ]
            }
        ]
    }
}

card_str = json.dumps(card, ensure_ascii=False)

records = mapping.get("records", {})
members = mapping.get("members", {})
all_ids = set(list(records.keys()) + list(members.keys()))

# Filter out name_pending members and sort for consistency
target_ids = [
    oid for oid, info in {**records, **members}.items()
    if info.get("name", "").lower() not in ("", "name_pending")
]

print(f"Will send to {len(target_ids)} members (excluding name_pending/empty)")
print(f"Course: {course['日期']} {course['开始和结束时间']} - {course['讲师']}")

import os
os.makedirs(STAMP_DIR, exist_ok=True)

results = []
for i, oid in enumerate(target_ids):
    stamp_file = f"{STAMP_DIR}/{oid}.json"
    if os.path.exists(stamp_file):
        print(f"[{i+1}/{len(target_ids)}] SKIP {oid} - already sent")
        results.append((oid, "skipped", "already_sent"))
        continue

    cmd = [
        "openclaw", "message",
        "--channel", "feishu",
        "--target", f"user:{oid}",
        "--card", card_str
    ]
    r = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
    if r.returncode == 0:
        # Try to extract message_id from stdout
        msg_id = ""
        try:
            out = json.loads(r.stdout)
            msg_id = out.get("message_id", "")
        except:
            pass
        with open(stamp_file, "w") as f:
            json.dump({"open_id": oid, "sent_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "message_id": msg_id}, f)
        print(f"[{i+1}/{len(target_ids)}] OK   {oid}")
        results.append((oid, "ok", msg_id))
    else:
        print(f"[{i+1}/{len(target_ids)}] FAIL {oid}: {r.stderr[:100]}")
        results.append((oid, "failed", r.stderr[:100]))
    time.sleep(1.2)

ok = sum(1 for _, s, _ in results if s == "ok")
skipped = sum(1 for _, s, _ in results if s == "skipped")
failed = sum(1 for _, s, _ in results if s == "failed")
print(f"\nDone: {ok} ok, {skipped} skipped, {failed} failed")