#!/usr/bin/env python3
# NodeSeek 自动签到 - 使用 OpenClaw browser 工具
# 通过 browser 工具控制 Chrome 浏览器签到

import json
import subprocess
import time
from datetime import datetime
from pathlib import Path

SCRIPT_DIR = Path(__file__).parent
STATE_FILE = SCRIPT_DIR / "nodeseek-checkin-state.json"

ACCOUNTS = {
    "朦胧": "dc4d1551406351a93c09082ea08e2d2e",
    "VP404": "3cfeb30b562daec31ba63bf64fdb3838"
}

def browser_cmd(action, **kwargs):
    """执行 OpenClaw browser 命令"""
    cmd = ["openclaw", "browser", action]
    for k, v in kwargs.items():
        cmd.extend([f"--{k}", str(v)])
    
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode == 0:
        try:
            return json.loads(result.stdout)
        except:
            return {"ok": True}
    return {"ok": False, "error": result.stderr}

def checkin_account(name, cookie, target_id):
    """签到单个账号"""
    print(f"[{name}] 签到中...")
    
    # 设置 Cookie
    set_cookie_js = f"async () => {{ document.cookie = '_nk={cookie}; domain=.nodeseek.com; path=/'; location.reload(); }}"
    browser_cmd("act", profile="openclaw", targetId=target_id, fn=set_cookie_js)
    time.sleep(3)
    
    # 执行签到
    checkin_js = "async () => { const res = await fetch('https://www.nodeseek.com/api/attendance?random=false', {method: 'POST', credentials: 'include'}); return await res.json(); }"
    result = browser_cmd("act", profile="openclaw", targetId=target_id, fn=checkin_js)
    
    if result.get("result", {}).get("success"):
        reward = result["result"].get("data", "未知")
        print(f"[{name}] ✅ 签到成功！奖励: {reward}")
        return {"status": "success", "reward": reward, "time": datetime.now().isoformat()}
    else:
        message = result.get("result", {}).get("message", "未知错误")
        print(f"[{name}] ❌ {message}")
        return {"status": "failed", "error": message, "time": datetime.now().isoformat()}

def main():
    # 检查今天是否已签到
    state = {}
    if STATE_FILE.exists():
        state = json.loads(STATE_FILE.read_text())
    
    today = datetime.now().strftime("%Y-%m-%d")
    if state.get("lastCheckin") == today and state.get("accounts"):
        print(f"今天已经签到过了 ({today})")
        for name, result in state.get("accounts", {}).items():
            status = result.get("status")
            detail = result.get("reward") or result.get("error", "N/A")
            print(f"  {name}: {status} ({detail})")
        return
    
    print(f"开始签到 NodeSeek ({today})...")
    
    # 启动浏览器
    browser_cmd("start", profile="openclaw")
    time.sleep(2)
    
    # 打开 NodeSeek
    result = browser_cmd("open", profile="openclaw", targetUrl="https://www.nodeseek.com")
    target_id = result.get("targetId")
    
    if not target_id:
        print("❌ 无法打开浏览器")
        return
    
    time.sleep(3)
    
    # 签到所有账号
    results = {}
    for name, cookie in ACCOUNTS.items():
        results[name] = checkin_account(name, cookie, target_id)
        time.sleep(3)
    
    # 保存状态
    state["lastCheckin"] = today
    state["accounts"] = results
    STATE_FILE.write_text(json.dumps(state, indent=2, ensure_ascii=False))
    
    print("\n签到完成！")
    for name, result in results.items():
        status = result.get("status")
        detail = result.get("reward") or result.get("error", "N/A")
        print(f"  {name}: {status} ({detail})")

if __name__ == "__main__":
    main()
