"""CRM session lifecycle: server-side revalidation of the signed cookie on every authenticated request.

The cookie is signed (not encrypted, not revocable). Everything that decides what a session may do is therefore re-read from
agents_v2 on each request - one primary-key lookup, no cache, no per-process state - so a change made by any worker or by dbshell
is effective everywhere on the next request:
  * the agent row is gone or is_active != 1                 -> session revoked
  * the password hash changed (fingerprint mismatch)        -> session revoked (every other open session of that user)
  * access_level changed                                    -> the session's level is refreshed (demotion/promotion)
  * idle > IDLE_SECONDS or age > ABSOLUTE_SECONDS            -> session expired (counters live in the cookie, so the shared
    Website cookie / PERMANENT_SESSION_LIFETIME are untouched)
  * cookie without these markers (issued before this guard)  -> refused once; the user logs in again.
The password fingerprint is HMAC-SHA256(SECRET_KEY, hash)[:32 hex]: it is not the hash, cannot be used to attack the password,
and rotating SECRET_KEY invalidates every session (as it already did).
If the database cannot be read the request is refused (503) and the session is kept: fail closed, no revocation on a blip.
"""
import hashlib
import hmac
import time

from flask import current_app, session

from modules.core.session_queries import get_agent_session_state

IDLE_SECONDS = 2 * 3600
ABSOLUTE_SECONDS = 12 * 3600
TOUCH_SECONDS = 60          # refresh the idle marker at most once a minute (avoids re-signing the cookie on every request)
CLOCK_SKEW_SECONDS = 120

KEY_LOGIN_AT = 'crm_login_at'
KEY_SEEN_AT = 'crm_seen_at'
KEY_PASSWORD = 'crm_pw'

MESSAGES = {
    'session_expired': 'Sesja wygasła. Zaloguj się ponownie.',
    'session_revoked': 'Sesja została zakończona. Zaloguj się ponownie.',
    'session_upgrade_required': 'Zaloguj się ponownie.',
    'session_check_unavailable': 'Nie można teraz zweryfikować sesji. Spróbuj ponownie.',
}


def _now():
    return time.time()


def password_fingerprint(password_hash):
    key = current_app.secret_key
    key = key.encode('utf-8') if isinstance(key, str) else bytes(key)
    message = b'crm-session-v1|' + str(password_hash or '').encode('utf-8')
    return hmac.new(key, message, hashlib.sha256).hexdigest()[:32]


def begin_session(password_hash):
    """Called by the login view right after the identity keys are stored in the session."""
    now = int(_now())
    session[KEY_LOGIN_AT] = now
    session[KEY_SEEN_AT] = now
    session[KEY_PASSWORD] = password_fingerprint(password_hash)


def refresh_password_fingerprint(new_password_hash):
    """The user changed THEIR OWN password: keep this session, every other session of the user dies on its next request."""
    session[KEY_PASSWORD] = password_fingerprint(new_password_hash)


def _number(value):
    return isinstance(value, (int, float)) and not isinstance(value, bool)


def _revoke(reason):
    session.clear()
    return reason, 403


def check_session():
    """None when the session may proceed, else (reason_code, http_status). Revoked sessions are cleared here."""
    login_at, seen_at, fingerprint = session.get(KEY_LOGIN_AT), session.get(KEY_SEEN_AT), session.get(KEY_PASSWORD)
    if not (_number(login_at) and _number(seen_at) and isinstance(fingerprint, str)):
        return _revoke('session_upgrade_required')

    now = _now()
    if (now - login_at > ABSOLUTE_SECONDS or now - seen_at > IDLE_SECONDS
            or login_at - now > CLOCK_SKEW_SECONDS or seen_at - now > CLOCK_SKEW_SECONDS):
        return _revoke('session_expired')

    try:
        state = get_agent_session_state(session.get('user_id'))
    except Exception as exc:
        current_app.logger.warning('CRM session check unavailable: %s', exc)
        return 'session_check_unavailable', 503

    if state is None or state['is_active'] != 1:
        return _revoke('session_revoked')
    if not hmac.compare_digest(fingerprint, password_fingerprint(state['password_hash'])):
        return _revoke('session_revoked')

    level = state['access_level'] or 'agent'
    if session.get('access_level') != level:
        session['access_level'] = level
    if now - seen_at >= TOUCH_SECONDS:
        session[KEY_SEEN_AT] = int(now)
    return None
