"""Trace-driven activation-compression policy units."""

import os

import pytest

from meshnet_node.activation_compression import (
    CompressionPolicies,
    CompressionPolicy,
    compress_activation,
    decompress_activation,
)


def test_compressible_body_uses_zstd_when_it_clears_savings_policy():
    body = b"activation" * 20_000
    result = compress_activation(body, CompressionPolicy(min_input_bytes=1, min_savings_bytes=100))
    assert result.encoding == "zstd"
    assert result.output_bytes < result.input_bytes
    assert decompress_activation(result.body, result.encoding).body == body


def test_incompressible_body_stays_raw_after_measured_trial():
    body = os.urandom(32 * 1024)
    result = compress_activation(body, CompressionPolicy(min_input_bytes=1, min_savings_bytes=1))
    assert result.encoding is None
    assert result.body == body
    assert result.decision == "below_savings"


def test_small_body_uses_raw_fast_path_without_zstd_trial():
    body = b"x" * 1024
    result = compress_activation(body, CompressionPolicy(min_input_bytes=2048))
    assert result.encoding is None
    assert result.decision == "below_min_input"
    assert result.elapsed_seconds >= 0


def test_threshold_requires_both_byte_and_ratio_savings():
    body = b"a" * 4096
    result = compress_activation(
        body, CompressionPolicy(min_input_bytes=1, min_savings_bytes=len(body), min_savings_ratio=0),
    )
    assert result.encoding is None
    assert result.decision == "below_savings"


def test_malformed_zstd_and_legacy_raw_bodies_are_handled_explicitly():
    assert decompress_activation(b"legacy", None).body == b"legacy"
    with pytest.raises(ValueError, match="invalid zstd activation body"):
        decompress_activation(b"not a zstd frame", "zstd")
    with pytest.raises(ValueError, match="unsupported"):
        decompress_activation(b"body", "gzip")


def test_prefill_decode_and_route_conditions_have_independent_config(monkeypatch):
    policies = CompressionPolicies()
    assert policies.for_condition("relay", "prefill").min_input_bytes < policies.for_condition("relay", "decode").min_input_bytes
    monkeypatch.setenv("MESHNET_COMPRESSION_RELAY_DECODE_MIN_INPUT_BYTES", "123")
    monkeypatch.setenv("MESHNET_COMPRESSION_LAN_PREFILL_ENABLED", "false")
    assert policies.for_condition("relay", "decode").min_input_bytes == 123
    assert not policies.for_condition("lan", "prefill").enabled
    assert policies.for_condition("benchmark", "prefill").enabled
