#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：session_manager.py
模块描述：会话管理器，用于在多次执行之间共享登录状态

作者：czj
创建日期：2026-07-11
"""

import logging
import os
from typing import Optional, Dict, Any
from datetime import datetime
from pathlib import Path

logger = logging.getLogger(__name__)

# 全局会话状态
_session_state = {
    "is_logged_in": False,
    "last_login_time": None,
    "cookies": None,
    "storage_state": None,
}


def get_session_state() -> Dict[str, Any]:
    """获取当前会话状态"""
    return _session_state.copy()


def set_logged_in(cookies: Optional[Dict] = None, storage_state: Optional[Dict] = None):
    """设置登录状态"""
    global _session_state
    _session_state["is_logged_in"] = True
    _session_state["last_login_time"] = datetime.now().isoformat()
    _session_state["cookies"] = cookies
    _session_state["storage_state"] = storage_state
    logger.info("Session state updated: logged in")


def clear_session():
    """清除会话状态"""
    global _session_state
    _session_state = {
        "is_logged_in": False,
        "last_login_time": None,
        "cookies": None,
        "storage_state": None,
    }
    logger.info("Session state cleared")


def is_session_valid() -> bool:
    """检查会话是否有效（登录且未过期）"""
    if not _session_state["is_logged_in"]:
        return False

    # 可以添加会话过期检查逻辑
    # 例如：检查last_login_time是否超过某个时间阈值

    return True