"""S1.1 regression tests: CRM session lifecycle (middleware/session_guard.py).

Every test uses the `crm_env` fixture, so the REAL guard runs against a real (temporary) agents.db and real logins; time is a
controllable clock. Users: master 101 (mia), agents 102 (ann) and 103 (bob).
"""
import re
import statistics
import time

import pytest

from InvestmentManager.middleware import session_guard
from tests.investmentmanager.conftest import CRM_ANN, CRM_BOB, CRM_MASTER, CRM_PASSWORDS

pytestmark = pytest.mark.crm_session_guard

PROTECTED = '/crm/alerts/get'                # any authenticated JSON endpoint
MASTER_ONLY = '/crm/offers/export-jobs/status'
HOUR = 3600


@pytest.fixture()
def clock(monkeypatch):
    state = {'now': time.time()}
    monkeypatch.setattr(session_guard, '_now', lambda: state['now'])
    return state


def _code(response):
    body = response.get_json(silent=True) or {}
    return body.get('code')


# ------------------------------------------------------------------------------------------------ login markers
def test_login_stores_markers_and_a_fingerprint_that_is_not_the_password_hash(app, crm_env, crm_login):
    from modules.core import storage_paths
    import sqlite3
    stored_hash = sqlite3.connect(storage_paths.agents_db_path()).execute('SELECT password_hash FROM agents_v2 WHERE id=?', (CRM_ANN,)).fetchone()[0]
    ann = crm_login(app, CRM_ANN)
    with ann.session_transaction() as session:
        assert isinstance(session['crm_login_at'], int) and session['crm_seen_at'] == session['crm_login_at']
        assert re.fullmatch(r'[0-9a-f]{32}', session['crm_pw']) and session['crm_pw'] not in stored_hash
        assert 'password_hash' not in session
    raw_cookie = ann.get_cookie('session').value
    assert stored_hash not in raw_cookie
    assert ann.get(PROTECTED).status_code == 200


def test_fingerprint_depends_on_the_secret_key_and_the_hash(app, crm_env):
    with app.test_request_context():
        first = session_guard.password_fingerprint('hash-a')
        assert first == session_guard.password_fingerprint('hash-a') != session_guard.password_fingerprint('hash-b')
        app.secret_key = 'another-secret'
        assert session_guard.password_fingerprint('hash-a') != first


# ------------------------------------------------------------------------------------------------ revocation
def test_deactivated_user_is_cut_off_on_the_next_request_including_writes(app, crm_env, crm_login, crm_set_agent):
    ann = crm_login(app, CRM_ANN)
    crm_set_agent(CRM_ANN, is_active=0)
    response = ann.post('/crm/alerts/mark_all_read')
    assert response.status_code == 403 and _code(response) == 'session_revoked'
    with ann.session_transaction() as session:
        assert 'user_id' not in session and 'access_level' not in session
    assert _code(ann.get(PROTECTED)) == 'auth_required'          # now simply unauthenticated


def test_deleted_user_is_cut_off(app, crm_env, crm_login):
    import sqlite3
    from modules.core import storage_paths
    ann = crm_login(app, CRM_ANN)
    conn = sqlite3.connect(storage_paths.agents_db_path())
    conn.execute('DELETE FROM agents_v2 WHERE id = ?', (CRM_ANN,))
    conn.commit()
    conn.close()
    assert _code(ann.post('/crm/knowledge/add_note', json={'title': 'ghost', 'content': 'x', 'is_private': False})) == 'session_revoked'


def test_html_navigation_of_a_revoked_session_redirects_to_login(app, crm_env, crm_login, crm_set_agent):
    ann = crm_login(app, CRM_ANN)
    crm_set_agent(CRM_ANN, is_active=0)
    response = ann.get('/crm/agents_panel_meta')
    assert response.status_code == 302 and response.headers['Location'].endswith('/crm/')


def test_password_change_by_master_ends_the_other_sessions_of_that_user(app, crm_env, crm_login):
    ann_laptop, ann_phone, master = crm_login(app, CRM_ANN), crm_login(app, CRM_ANN), crm_login(app, CRM_MASTER)
    assert master.post(f'/crm/change_password/{CRM_ANN}', data={'new_password': 'brand-new-pass'}).status_code == 200
    for session_client in (ann_laptop, ann_phone):
        assert _code(session_client.get(PROTECTED)) == 'session_revoked'
    fresh = app.test_client()
    assert fresh.post('/crm/', data={'username': 'ann', 'password': 'brand-new-pass'}).status_code == 302
    assert fresh.get(PROTECTED).status_code == 200


def test_master_changing_their_own_password_keeps_only_the_current_session(app, crm_env, crm_login):
    here, elsewhere = crm_login(app, CRM_MASTER), crm_login(app, CRM_MASTER)
    assert here.post(f'/crm/change_password/{CRM_MASTER}', data={'new_password': 'brand-new-pass'}).status_code == 200
    assert here.get(PROTECTED).status_code == 200
    assert _code(elsewhere.get(PROTECTED)) == 'session_revoked'


def test_own_password_change_through_the_profile_keeps_this_session_only(app, crm_env, crm_login):
    here, elsewhere = crm_login(app, CRM_ANN), crm_login(app, CRM_ANN)
    response = here.post('/crm/update_profile', data={
        'email': 'ann@example.invalid', 'telefon': '600102', 'licencja': 'LIC-102',
        'current_password': CRM_PASSWORDS[CRM_ANN], 'new_password': 'brand-new-pass', 'confirm_password': 'brand-new-pass'})
    assert response.status_code in (200, 302)
    assert here.get(PROTECTED).status_code == 200
    assert _code(elsewhere.get(PROTECTED)) == 'session_revoked'


def test_password_changed_directly_in_the_database_also_revokes(app, crm_env, crm_login, crm_set_agent):
    ann = crm_login(app, CRM_ANN)
    crm_set_agent(CRM_ANN, password_hash='pbkdf2:sha256:1$x$y')          # what dbshell / an administrator could do
    assert _code(ann.get(PROTECTED)) == 'session_revoked'


# ------------------------------------------------------------------------------------------------ role changes
def test_demoted_master_loses_master_rights_without_logging_in_again(app, crm_env, crm_login, crm_set_agent):
    master = crm_login(app, CRM_MASTER)
    assert master.get(MASTER_ONLY).status_code == 200
    crm_set_agent(CRM_MASTER, access_level='agent')
    assert master.get(MASTER_ONLY).status_code == 403
    with master.session_transaction() as session:
        assert session['access_level'] == 'agent'


def test_promoted_agent_gains_the_new_level_and_admin_stays_what_the_database_says(app, crm_env, crm_login, crm_set_agent):
    bob = crm_login(app, CRM_BOB)
    assert bob.get(MASTER_ONLY).status_code == 403
    crm_set_agent(CRM_BOB, access_level='master')
    assert bob.get(MASTER_ONLY).status_code == 200
    crm_set_agent(CRM_BOB, access_level='admin')                          # legacy value: kept as is, no new powers
    assert bob.get(MASTER_ONLY).status_code == 403
    with bob.session_transaction() as session:
        assert session['access_level'] == 'admin'


# ------------------------------------------------------------------------------------------------ time limits
def test_idle_limit_expires_the_session_but_activity_keeps_it_alive(app, crm_env, crm_login, clock):
    ann = crm_login(app, CRM_ANN)
    for _ in range(4):                                                      # 4 x 1h45 = 7h of work with pauses below the limit
        clock['now'] += 1.75 * HOUR
        assert ann.get(PROTECTED).status_code == 200
    clock['now'] += 2 * HOUR + 5                                            # now idle for more than 2 hours
    response = ann.get(PROTECTED)
    assert response.status_code == 403 and _code(response) == 'session_expired'
    with ann.session_transaction() as session:
        assert 'user_id' not in session


def test_idle_boundary(app, crm_env, crm_login, clock):
    ann = crm_login(app, CRM_ANN)
    clock['now'] += 2 * HOUR - 5
    assert ann.get(PROTECTED).status_code == 200


def test_absolute_limit_expires_even_a_continuously_active_session(app, crm_env, crm_login, clock):
    ann = crm_login(app, CRM_ANN)
    for _ in range(7):                                                      # 7 x 1h30 = 10h30, always active
        clock['now'] += 1.5 * HOUR
        assert ann.get(PROTECTED).status_code == 200
    clock['now'] += 1.5 * HOUR + 5                                          # 12h0m5s since login
    assert _code(ann.get(PROTECTED)) == 'session_expired'


def test_idle_marker_is_refreshed_at_most_once_a_minute(app, crm_env, crm_login, clock):
    ann = crm_login(app, CRM_ANN)
    with ann.session_transaction() as session:
        first = session['crm_seen_at']
    clock['now'] += 30
    ann.get(PROTECTED)
    with ann.session_transaction() as session:
        assert session['crm_seen_at'] == first
    clock['now'] += 31
    ann.get(PROTECTED)
    with ann.session_transaction() as session:
        assert session['crm_seen_at'] > first


def test_timestamps_from_the_future_are_refused(app, crm_env, crm_login, clock):
    ann = crm_login(app, CRM_ANN)
    with ann.session_transaction() as session:
        session['crm_login_at'] = int(clock['now']) + 3600
    assert _code(ann.get(PROTECTED)) == 'session_expired'


# ------------------------------------------------------------------------------------------------ cookies issued before the guard
def test_cookie_without_guard_markers_is_refused_once(app, crm_env):
    client = app.test_client()
    with client.session_transaction() as session:                          # what every pre-S1.1 cookie looks like
        session.update({'user_id': CRM_ANN, 'access_level': 'agent', 'username': 'ann'})
    response = client.get(PROTECTED)
    assert response.status_code == 403 and _code(response) == 'session_upgrade_required'
    with client.session_transaction() as session:
        assert 'user_id' not in session
    assert client.post('/crm/', data={'username': 'ann', 'password': CRM_PASSWORDS[CRM_ANN]}).status_code == 302
    assert client.get(PROTECTED).status_code == 200


def test_tampered_fingerprint_is_refused(app, crm_env, crm_login):
    ann = crm_login(app, CRM_ANN)
    with ann.session_transaction() as session:
        session['crm_pw'] = '0' * 32
    assert _code(ann.get(PROTECTED)) == 'session_revoked'


def test_a_cookie_cannot_be_reused_for_another_user_id(app, crm_env, crm_login):
    """Swapping user_id inside a validly signed cookie (impossible without the key) would still fail the fingerprint."""
    ann = crm_login(app, CRM_ANN)
    with ann.session_transaction() as session:
        session['user_id'] = CRM_MASTER
        session['access_level'] = 'master'
    assert _code(ann.get(MASTER_ONLY)) == 'session_revoked'


# ------------------------------------------------------------------------------------------------ failure mode
def test_unreadable_database_fails_closed_without_revoking(app, crm_env, crm_login, monkeypatch):
    ann = crm_login(app, CRM_ANN)

    def broken(_):
        raise RuntimeError('database is locked')
    with monkeypatch.context() as patch:          # (monkeypatch.undo() would also drop crm_env's DATA_DIR isolation)
        patch.setattr(session_guard, 'get_agent_session_state', broken)
        response = ann.get(PROTECTED)
    assert response.status_code == 503 and _code(response) == 'session_check_unavailable'
    assert ann.get(PROTECTED).status_code == 200                           # a blip does not log everybody out


# ------------------------------------------------------------------------------------------------ several workers
def test_another_worker_sees_a_change_immediately(app, crm_env, crm_login, crm_set_agent):
    """The guard keeps no per-process state: a second application instance (= another worker) shares only the database."""
    from modules.core.app_factory import create_app
    other = create_app()
    other.config['TESTING'] = True
    master = crm_login(app, CRM_MASTER)
    twin = other.test_client()
    twin.set_cookie('session', master.get_cookie('session').value, domain='localhost')
    assert twin.get(MASTER_ONLY).status_code == 200
    crm_set_agent(CRM_MASTER, access_level='agent')
    assert twin.get(MASTER_ONLY).status_code == 403
    crm_set_agent(CRM_MASTER, is_active=0)
    assert _code(twin.get(PROTECTED)) == 'session_revoked'


# ------------------------------------------------------------------------------------------------ cost
def test_validation_cost_per_request_is_small(app, crm_env, crm_login):
    ann = crm_login(app, CRM_ANN)
    with ann.session_transaction() as session:
        snapshot = dict(session)
    samples = []
    for _ in range(300):
        with app.test_request_context('/crm/alerts/get'):
            from flask import session as request_session
            request_session.update(snapshot)
            started = time.perf_counter()
            assert session_guard.check_session() is None
            samples.append((time.perf_counter() - started) * 1000)
    median = statistics.median(samples)
    print(f'\ncheck_session median {median:.3f} ms, p95 {sorted(samples)[285]:.3f} ms over {len(samples)} calls')
    assert median < 5.0


# ------------------------------------------------------------------------------------------------ documented limit
def test_known_limit_a_copied_cookie_survives_logout_until_a_limit_or_revocation_applies(app, crm_env, crm_login):
    """Signed-cookie sessions cannot be revoked per cookie: logout only clears the browser's copy. Exposure is bounded by the 2 h idle /
    12 h absolute limits and by deactivation / password change. Closing it fully needs a server-side session table (a migration),
    deliberately NOT part of S1."""
    ann = crm_login(app, CRM_ANN)
    stolen = ann.get_cookie('session').value
    ann.get('/crm/logout')
    thief = app.test_client()
    thief.set_cookie('session', stolen, domain='localhost')
    assert thief.get(PROTECTED).status_code == 200
