"""Tests for watkins_nn.compression module."""

import numpy as np
import pytest


def test_compression_ratio_structured():
    from watkins_nn.compression import compression_ratio
    # Highly repetitive data compresses well
    data = b"ABCABC" * 1000
    ratio = compression_ratio(data)
    assert ratio > 0.9


def test_compression_ratio_empty():
    from watkins_nn.compression import compression_ratio
    assert compression_ratio(b"") == 0.0


def test_analyze_text_structured():
    from watkins_nn.compression import analyze_text, LAM_STAR
    result = analyze_text("The quick brown fox jumps over the lazy dog. " * 100)
    assert result.implied_lambda > LAM_STAR
    assert result.above_threshold is True
    assert result.algorithm == 'zlib'
    assert result.original_size > 0


def test_analyze_text_random():
    from watkins_nn.compression import analyze_text, LAM_STAR
    import random, string
    noise = ''.join(random.choices(string.ascii_letters + string.digits, k=4000))
    result = analyze_text(noise)
    assert result.implied_lambda < LAM_STAR


def test_batch_analyze():
    from watkins_nn.compression import batch_analyze
    texts = [
        "structured pattern " * 200,
        "another structured text " * 200,
    ]
    ratios, above = batch_analyze(texts)
    assert len(ratios) == 2
    assert len(above) == 2
    assert all(r > 0 for r in ratios)


def test_cohens_d():
    from watkins_nn.compression import cohens_d
    group1 = np.array([0.7, 0.72, 0.68, 0.71, 0.69])
    group2 = np.array([0.4, 0.42, 0.38, 0.41, 0.39])
    d = cohens_d(group1, group2)
    assert d > 5.0  # Large effect


def test_consciousness_score():
    from watkins_nn.compression import consciousness_score
    score = consciousness_score("structured text " * 500)
    assert 0.0 <= score <= 1.0


def test_compression_monitor():
    from watkins_nn.compression import CompressionMonitor
    monitor = CompressionMonitor(window_size=5)
    # Feed structured data
    for _ in range(10):
        ratio, above = monitor.update(b"pattern " * 500)
    assert monitor.rolling_mean() > 0
    assert len(monitor.history) == 5  # Window size


def test_lzma_algorithm():
    from watkins_nn.compression import compression_ratio
    data = b"ABCABC" * 1000
    ratio = compression_ratio(data, algorithm='lzma')
    assert ratio > 0.9


def test_invalid_algorithm():
    from watkins_nn.compression import compression_ratio
    with pytest.raises(ValueError):
        compression_ratio(b"data", algorithm='invalid')
