#!/usr/bin/env python3
# NodeSeek 签到 - 增强版（模拟真实浏览器）

import json
import urllib.request
import urllib.error
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 checkin_account(name, cookie):
    print(f"[{name}] 签到中...")
    
    try:
        req = urllib.request.Request(
            "https://www.nodeseek.com/api/attendance?random=false",
            method="POST",
            headers={
                "Cookie": f"_nk={cookie}",
                "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36",
                "Accept": "application/json, text/plain, */*",
                "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
                "Accept-Encoding": "gzip, deflate, br",
                "Referer": "https://www.nodeseek.com/",
                "Origin": "https://www.nodeseek.com",
                "Sec-Fetch-Dest": "empty",
                "Sec-Fetch-Mode": "cors",
                "Sec-Fetch-Site": "same-origin",
                "sec-ch-ua": '"Google Chrome";v="145", "Chromium";v="145", "Not-A.Brand";v="99"',
                "sec-ch-ua-mobile": "?0",
                "sec-ch-ua-platform": '"macOS"'
            }
        )
        
        with urllib.request.urlopen(req, timeout=10) as response:
            data = json.loads(response.read().decode())
        
        if data.get("success"):
            reward = data.get("data", "未知")
            print(f"[{name}] ✅ 签到成功！奖励: {reward}")
            return {"status": "success", "reward": reward, "time": datetime.now().isoformat()}
        else:
            message = data.get("message", "未知错误")
            print(f"[{name}] ❌ 签到失败: {message}")
            return {"status": "failed", "error": message, "time": datetime.now().isoformat()}
    
    except urllib.error.HTTPError as e:
        print(f"[{name}] ❌ HTTP {e.code}: {e.reason}")
        return {"status": "error", "error": f"HTTP {e.code}", "time": datetime.now().isoformat()}
    except Exception as e:
        print(f"[{name}] ❌ 请求失败: {e}")
        return {"status": "error", "error": str(e), "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})...")
    
    results = {}
    for name, cookie in ACCOUNTS.items():
        results[name] = checkin_account(name, cookie)
        import time
        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()
