"""
Session utilities for Flask-Session integration with Dash.

This module provides functions to store and retrieve authentication data
from Flask server-side sessions, enabling session persistence across
requests, page refreshes, and multi-worker deployments.
"""
from datetime import datetime
from flask import session, has_request_context
from typing import Optional, Dict, Any

from bfabric_web_apps.utils.config import settings


def store_token_in_session(token: str, token_data: dict) -> None:
    """
    Store token and token_data in Flask session.

    Args:
        token: The authentication token string
        token_data: The validated token data dictionary
    """
    if has_request_context():
        session['token'] = token
        session['token_data'] = token_data
        session['session_created_at'] = datetime.now().isoformat()
        session['last_activity'] = datetime.now().isoformat()
        session.modified = True


def touch_session() -> None:
    """
    Update last activity timestamp to extend session lifetime.

    Call this on user activity to prevent session timeout during
    long-running operations.
    """
    if has_request_context() and 'token_data' in session:
        session['last_activity'] = datetime.now().isoformat()
        session.modified = True


def get_token_from_session() -> Optional[str]:
    """
    Retrieve token from Flask session.

    Returns:
        The token string or None if not in session
    """
    if has_request_context():
        return session.get('token')
    return None


def get_token_data_from_session() -> Optional[Dict[str, Any]]:
    """
    Retrieve token_data from Flask session.

    Returns:
        The token_data dict or None if not in session
    """
    if has_request_context():
        return session.get('token_data')
    return None


def clear_session() -> None:
    """Clear all session data (logout)."""
    if has_request_context():
        session.clear()


def is_session_authenticated() -> bool:
    """
    Check if session has valid authentication.

    Returns:
        True if session contains token_data, False otherwise
    """
    return get_token_data_from_session() is not None
