#!/usr/bin/env python3
"""
Social Layer 每日社区回顾发送脚本
直接调用 Feishu API 发送日环比回顾到课程答疑群
"""

import os
import json
import requests
from datetime import datetime

# ========== 配置 ==========
BOT_TOKEN = os.environ.get("FEISHU_BOT_TOKEN", "")
REVIEW_TARGET_CHAT_ID = "oc_68f54d44d13dcce10373cd04db7a81e7"  # 课程答疑群
TOKEN_FILE = "/home/ubuntu/.openclaw/workspace/projects/openclaw-cn-tutorial/courses/social-layer/dairy/.last_send_daily_review_oc_68f54d44.txt"
DAIRY_DIR = "/home/ubuntu/.openclaw/workspace/projects/openclaw-cn-tutorial/courses/social-layer/dairy"
STUDENTS_DIR = "/home/ubuntu/.openclaw/workspace/projects/openclaw-cn-tutorial/courses/social-layer/students"

FEISHU_SEND_MSG_URL = "https://open.feishu.cn/open-apis/im/v1/messages"
FEISHU_UPLOAD_URL = "https://open.feishu.cn/open-apis/im/v1/images"

# ========== 工具函数 ==========

def get_bot_token():
    """获取 Feishu bot token"""
    if BOT_TOKEN:
        return BOT_TOKEN
    # 从环境变量或配置文件读取
    token_file = os.path.expanduser("~/.openclaw/feishu_token.json")
    if os.path.exists(token_file):
        with open(token_file) as f:
            data = json.load(f)
            return data.get("bot_access_token", "")
    return ""

def get_today_date():
    """获取今天日期 (Asia/Shanghai)"""
    from datetime import datetime
    import pytz
    tz = pytz.timezone("Asia/Shanghai")
    return datetime.now(tz).strftime("%Y-%m-%d")

def read_daily_log(date_str):
    """读取当日日志"""
    path = os.path.join(DAIRY_DIR, f"{date_str}.md")
    if os.path.exists(path):
        with open(path) as f:
            return f.read()
    return None

def check_already_sent(date_str):
    """检查今日是否已发送"""
    if not os.path.exists(TOKEN_FILE):
        return False
    with open(TOKEN_FILE) as f:
        content = f.read().strip()
        return date_str in content

def write_sent_stamp(date_str):
    """写入发送时间戳"""
    with open(TOKEN_FILE, "w") as f:
        f.write(f"SENT {datetime.utcnow().isoformat()}Z\nDATE {date_str}\n")

def extract_review_content(log_content):
    """从日志中提取回顾内容（简化版）"""
    if not log_content:
        return "今日暂无新的社区互动记录。"
    
    lines = log_content.split("\n")
    result = []
    in_overview = False
    in_details = False
    
    for line in lines:
        if "## 今日概况" in line:
            in_overview = True
            in_details = False
            result.append(line)
        elif "## 同学互动详情" in line:
            in_overview = False
            in_details = True
            result.append(line)
        elif line.startswith("## ") and "概况" not in line and "详情" not in line:
            in_overview = False
            in_details = False
        elif in_overview or in_details:
            result.append(line)
    
    return "\n".join(result) if result else log_content[:3000]

def send_feishu_message(content):
    """发送飞书消息"""
    token = get_bot_token()
    if not token:
        print("ERROR: No bot token available")
        return False
    
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "receive_id": REVIEW_TARGET_CHAT_ID,
        "msg_type": "text",
        "content": json.dumps({"text": content})
    }
    
    resp = requests.post(FEISHU_SEND_MSG_URL, headers=headers, json=payload, params={"receive_id_type": "chat_id"})
    
    if resp.status_code == 200:
        data = resp.json()
        if data.get("code") == 0:
            print(f"SUCCESS: Message sent, msg_id={data.get('data', {}).get('message_id')}")
            return True
        else:
            print(f"ERROR: Feishu API error: {data.get('msg')}")
            return False
    else:
        print(f"ERROR: HTTP {resp.status_code}: {resp.text}")
        return False

def main():
    today = get_today_date()
    print(f"Today (Asia/Shanghai): {today}")
    
    # 检查是否已发送
    if check_already_sent(today):
        print("今日已发送过社区回顾，跳过。")
        return
    
    # 读取日志
    log = read_daily_log(today)
    if not log:
        print(f"未找到 {today} 的日志文件，跳过。")
        return
    
    # 生成回顾内容
    review = extract_review_content(log)
    
    # 发送
    if send_feishu_message(review):
        write_sent_stamp(today)
    else:
        print("发送失败，未写入 stamp。")

if __name__ == "__main__":
    main()
