"""modules/core/password_policy.py: initial-password generator and the single policy for NEW passwords."""
import secrets
from collections import Counter

import pytest

from modules.core import password_policy as policy
from modules.core.password_policy import generate_initial_password, validate_new_password

ACCOUNT = dict(login='Jan.Kowalski', first_name='Jan', last_name='Kowalski', email='jan.kowalski@example.test', phone='+48 600 100 200', licence='LIC-12345')
CONFUSABLE = set('0O1lIoi')


# ------------------------------------------------------------------------------------------------ generator
def test_generated_passwords_have_the_required_shape():
    for _ in range(300):
        password = generate_initial_password()
        assert len(password) == 16
        assert set(password) <= set(policy.ALPHABET) and not (set(password) & CONFUSABLE)
        assert any(c.isupper() for c in password) and any(c.islower() for c in password) and any(c.isdigit() for c in password)


def test_generated_passwords_are_unique_and_unpredictable():
    batch = [generate_initial_password() for _ in range(2000)]
    assert len(set(batch)) == len(batch)
    assert len(set(policy.ALPHABET)) == len(policy.ALPHABET) == 55
    # every alphabet character shows up in every position over a large sample (no positional bias / constant parts)
    for position in range(16):
        assert len({password[position] for password in batch}) > 40


def test_generator_uses_secrets_and_never_account_data(monkeypatch):
    calls = []
    real = secrets.choice
    monkeypatch.setattr(policy.secrets, 'choice', lambda seq: (calls.append(1), real(seq))[1])
    password = generate_initial_password()
    assert len(calls) >= 16                                                         # every character comes from secrets.choice
    assert validate_new_password(password, **ACCOUNT) is None                       # a generated password satisfies the policy itself


def test_generated_password_satisfies_the_policy_for_any_account():
    for _ in range(200):
        assert validate_new_password(generate_initial_password(), **ACCOUNT) is None


# ------------------------------------------------------------------------------------------------ policy
@pytest.mark.parametrize('password', ['', 'short', 'Abcdefgh12!', 'x' * 11, None, 12345678901234])
def test_too_short_or_not_text_is_rejected(password):
    assert validate_new_password(password, **ACCOUNT) == policy.MESSAGE_TOO_SHORT


@pytest.mark.parametrize('password', [
    'Jan.Kowalski', 'jan.kowalski', 'JAN.KOWALSKI', 'Jan Kowalski', 'kowalski.jan', 'jan-kowalski', 'jan_kowalski',
    'jan.kowalski@example.test', 'JAN.KOWALSKI@EXAMPLE.TEST', '+48 600 100 200', '+48 (600) 100-200',
])
def test_login_and_obvious_identity_data_are_rejected(password):
    assert len(password) >= policy.PASSWORD_MIN_LENGTH
    assert validate_new_password(password, **ACCOUNT) == policy.MESSAGE_PREDICTABLE


LONG = dict(login='Aleksander.Wojciechowski', first_name='Aleksander', last_name='Wojciechowski', email='a.wojciechowski@example.test',
            phone='0048 601 234 567', licence='NR-LICENCJI-2026')


@pytest.mark.parametrize('password', ['Aleksander.Wojciechowski', 'aleksanderwojciechowski', 'WOJCIECHOWSKI-ALEKSANDER', 'Wojciechowski.Aleksander',
                                      'a.wojciechowski@example.test', 'a.wojciechowski@example.test'.upper(), '0048601234567', '+0048 (601) 234-567',
                                      'NR-LICENCJI-2026', 'nrlicencji2026'])
def test_concatenations_phone_and_licence_are_rejected_for_a_longer_account(password):
    assert len(password) >= policy.PASSWORD_MIN_LENGTH
    assert validate_new_password(password, **LONG) == policy.MESSAGE_PREDICTABLE


@pytest.mark.parametrize('password', ['lic-12345', 'LIC12345', 'jan', 'kowalski', 'jankowalski', 'KowalskiJan', '48600100200'])
def test_short_identity_values_fall_under_the_length_rule(password):
    assert validate_new_password(password, **ACCOUNT) == policy.MESSAGE_TOO_SHORT


def test_identity_check_is_case_and_separator_insensitive_but_not_a_substring_ban():
    assert validate_new_password('Jan.Kowalski', login='Jan.Kowalski') == policy.MESSAGE_PREDICTABLE
    assert validate_new_password('jan kowalski', login='Jan.Kowalski') == policy.MESSAGE_PREDICTABLE
    assert validate_new_password('Jan.Kowalski-2026!', **ACCOUNT) is None             # equal-to rule only, as decided (no substring ban)
    assert validate_new_password('correct horse battery', **ACCOUNT) is None


def test_ordinary_strong_passwords_pass_and_missing_account_data_is_tolerated():
    assert validate_new_password('Zażółć gęślą jaźń 2026', **ACCOUNT) is None
    assert validate_new_password('abcdefghijkl') is None
    assert validate_new_password('abcdefghijkl', login=None, first_name=None, last_name=None, email=None, phone=None, licence=None) is None


def test_polish_letters_are_compared_correctly():
    assert validate_new_password('Łukasz.Żółć-Wąs', login='Łukasz.Żółć-Wąs') == policy.MESSAGE_PREDICTABLE
    assert validate_new_password('ŁUKASZŻÓŁĆWĄS', login='Łukasz.Żółć-Wąs') == policy.MESSAGE_PREDICTABLE


def test_policy_constants_match_the_decision():
    assert policy.PASSWORD_MIN_LENGTH == 12 and policy.PASSWORD_GENERATED_LENGTH == 16
    assert Counter(policy.ALPHABET).most_common(1)[0][1] == 1
