"""Pytest suite for BioacousticModelSwapSlot and v2 Neural SoundStream/Encodec RVQ."""

from __future__ import annotations

try:
    import torch  # noqa: F401
except Exception:
    pass

import numpy as np
import pytest

from dolphingemma_bridge import (
    BioacousticModelSwapSlot,
    DolphinGemmaBridge,
    SCT04PocketScoutHydrophoneProfile,
    SoundStreamRVQTokenizer,
    verify_dolphingemma_model_identity,
)


def test_model_identity_guard_blocks_eric_hartford_text_llm() -> None:
    bad = verify_dolphingemma_model_identity("dphn/dolphin-2.9.4-gemma2-2b")
    assert bad["valid"] is False
    assert bad["is_bioacoustic_model"] is False
    assert bad["rejection_reason"] == "TEXT_ONLY_ERIC_HARTFORD_DOLPHIN_LLM"

    for good_id in (
        "google/dolphingemma",
        "facebook/encodec_24khz",
        "EarthSpeciesProject/NatureLM-audio",
        "EarthSpeciesProject/esp-aves2-eat-bio",
        "google/perch",
    ):
        ok = verify_dolphingemma_model_identity(good_id)
        assert ok["valid"] is True
        assert ok["is_bioacoustic_model"] is True


def test_bioacoustic_model_swap_slot_zero_residual_vram(tmp_path) -> None:
    sr = 192000
    t = np.linspace(0.0, 0.25, int(0.25 * sr), endpoint=False)
    # Synthetic 192 kHz FM whistle + ultrasonic click harmonic
    x = 0.6 * np.sin(2 * np.pi * (8000.0 + 6000.0 * t) * t) + 0.3 * np.sin(2 * np.pi * 64000.0 * t)

    slot = BioacousticModelSwapSlot(
        model_id="google/dolphingemma",
        device_policy="auto",
        receipt_path=tmp_path / "swap_slot.json",
    )
    with slot as engine:
        res = engine.encode_and_quantize_waveform(x, sr)
        assert res["codes_matrix"].shape[0] == 4
        assert len(res["rvq_tokens"]) > 0
        assert res["rvq_tokens"][0].startswith("[RVQ:L0_")
        assert res["embedding_128d"].shape == (128,)
        assert np.isfinite(res["reconstruction_snr_db"])

    assert slot.engine is None
    receipt = slot.last_swap_receipt
    assert receipt["schema"] == "masidyn_bioacoustic_swap.v1"
    assert receipt["post_exit_cuda_allocated_bytes"] == 0
    assert receipt["zero_residual_vram_verified"] is True
    assert receipt["masidyn_routing_undisturbed"] is True


def test_dolphingemma_bridge_v2_causal_transformer_prediction() -> None:
    bridge = DolphinGemmaBridge(model_id="google/dolphingemma")
    out = bridge.predict_next_acoustic_tokens(
        ["[RVQ:L0_010:L1_020:L2_030:L3_040]", "[RVQ:L0_012:L1_022:L2_031:L3_041]"],
        hull_id="BC-01",
        num_predictions=4,
    )
    assert out["marginal_spend_usd"] == 0.0
    assert len(out["predicted_tokens"]) == 4
    assert all(tok.startswith("[RVQ:L0_") for tok in out["predicted_tokens"])
    assert out["mean_entropy_bits"] > 0.0
    assert out["causal_perplexity"] >= 1.0
    assert out["swap_slot_receipt"]["post_exit_cuda_allocated_bytes"] == 0
    assert out["swap_slot_receipt"]["masidyn_routing_undisturbed"] is True


def test_sct04_pocket_scout_and_v1_tokenizer_compat() -> None:
    scout = SCT04PocketScoutHydrophoneProfile()
    aut = scout.verify_scout_autonomy()
    assert aut["valid_scout"] is True
    assert aut["carries_own_connection"] is True

    tok = SoundStreamRVQTokenizer()
    w = tok.tokenize_whistle_contour(5000.0, 11000.0, 12500.0, 600.0, inflections=1)
    assert w.startswith("[WHISTLE_CONTOUR:")


def test_causal_transformer_training_and_checkpoint_roundtrip(tmp_path) -> None:
    ckpt_file = tmp_path / "test_bioacoustic_rvq.pt"
    # Repeating periodic RVQ sequence so next-token training reduces cross-entropy loss
    train_seqs = [[(t % 8) for t in range(32)] for _ in range(16)]
    heldout_seqs = [[(t % 8) for t in range(24)] for _ in range(4)]

    slot1 = BioacousticModelSwapSlot(
        model_id="google/dolphingemma",
        device_policy="cpu",
        receipt_path=tmp_path / "slot1.json",
    )
    with slot1 as eng1:
        tr_info = eng1.fit_causal_transformer(train_seqs, epochs=6, lr=1e-2)
        assert tr_info["trained"] is True
        assert tr_info["final_train_nll_nats"] < tr_info["initial_train_nll_nats"]
        ev_info = eng1.evaluate_causal_sequences(heldout_seqs)
        assert ev_info["evaluated"] is True
        assert ev_info["heldout_perplexity"] < ev_info["uniform_codebook_baseline_perplexity"]
        save_info = eng1.save_checkpoint(ckpt_file)
        assert save_info["saved"] is True

    slot2 = BioacousticModelSwapSlot(
        model_id="google/dolphingemma",
        checkpoint_path=ckpt_file,
        slot_id="test_roundtrip_slot",
        device_policy="cpu",
        receipt_path=tmp_path / "slot2.json",
    )
    with slot2 as eng2:
        assert eng2.weight_source == "loaded_checkpoint"
        assert eng2.checkpoint_sha256 == save_info["checkpoint_sha256"]
        ev2 = eng2.evaluate_causal_sequences(heldout_seqs, train_l0_sequences=train_seqs)
        assert abs(ev2["heldout_nll_nats"] - ev_info["heldout_nll_nats"]) < 1e-5
        assert ev2["train_bigram_markov_baseline_perplexity"] is not None

    assert slot2.last_swap_receipt["slot_id"] == "test_roundtrip_slot"
    assert slot2.last_swap_receipt["weight_source"] == "loaded_checkpoint"
    assert slot2.last_swap_receipt["checkpoint_sha256"] == save_info["checkpoint_sha256"]
    assert (
        slot2.last_swap_receipt["checkpoint_parameter_audit"]["loaded_parameter_count"]
        == slot2.last_swap_receipt["checkpoint_parameter_audit"]["expected_parameter_count"]
    )
    assert slot2.last_swap_receipt["post_exit_cuda_allocated_bytes"] == 0


def test_checkpoint_loader_rejects_empty_partial_or_wrong_shape_payloads(tmp_path) -> None:
    import torch

    empty_ckpt = tmp_path / "empty.pt"
    torch.save({}, str(empty_ckpt))

    unrelated_ckpt = tmp_path / "unrelated.pt"
    torch.save({"foo": torch.zeros(4, 4)}, str(unrelated_ckpt))

    partial_ckpt = tmp_path / "partial.pt"
    torch.save({"codebooks.0": torch.zeros(128, 64)}, str(partial_ckpt))

    slot = BioacousticModelSwapSlot(
        model_id="google/dolphingemma",
        device_policy="cpu",
        receipt_path=tmp_path / "slot_reject.json",
    )
    with slot as eng:
        for bad_path in (empty_ckpt, unrelated_ckpt, partial_ckpt):
            with pytest.raises(ValueError):
                eng.load_checkpoint(bad_path)
            assert eng.weight_source != "loaded_checkpoint"


def test_state_hash_frozen_vs_adapted_and_coverage_metrics(tmp_path) -> None:
    slot = BioacousticModelSwapSlot(
        model_id="google/dolphingemma",
        device_policy="cpu",
        receipt_path=tmp_path / "slot_hash.json",
    )
    with slot as eng:
        h0 = eng.compute_state_hash()
        assert h0["weights_modified_since_init_or_load"] is False
        # Evaluate long sequences (>64 tokens) to verify both vocab context coverage and sequence-length position coverage
        train_seqs = [[(t % 6) for t in range(40)] for _ in range(8)]
        heldout_seqs = [[(t % 6) for t in range(100)] for _ in range(2)]
        ev_frozen = eng.evaluate_causal_sequences(heldout_seqs, max_seq_len=64, train_l0_sequences=train_seqs)
        assert ev_frozen["weights_modified_since_init_or_load"] is False
        assert ev_frozen["evaluated_next_token_positions"] == 2 * 63
        assert ev_frozen["total_available_next_token_positions"] == 2 * 99
        assert abs(ev_frozen["heldout_sequence_length_position_coverage_ratio"] - (126.0 / 198.0)) < 1e-3
        assert ev_frozen["heldout_bigram_context_vocab_coverage_ratio"] == 1.0

        eng.fit_causal_transformer(train_seqs, epochs=2, lr=5e-3)
        h1 = eng.compute_state_hash()
        assert h1["weights_modified_since_init_or_load"] is True
        assert h1["state_sha256"] != h0["state_sha256"]

    assert slot.last_swap_receipt["weights_modified_during_slot"] is True
