"""Measure causal decode on the pinned MOSS Audio Tokenizer v2 checkpoint."""

import argparse
import json
import math
import statistics
import time
from copy import deepcopy
from pathlib import Path

import numpy as np
import soundfile as sf
import torch
import torch.nn.functional as F
import transformers
from huggingface_hub import snapshot_download
from transformers import AutoModel


REPO = "OpenMOSS-Team/MOSS-Audio-Tokenizer-v2"
REVISION = "f6e20e543b33d2c252a7ef71bdf8aa71e5ff9169"
SAMPLE_RATE = 48_000
SAMPLES_PER_FRAME = 3_840
TOTAL_FRAMES = 153
CHUNK_SIZES = (1, 2, 4, 8)


def load_model(snapshot, precision, backend):
    model = AutoModel.from_pretrained(
        str(snapshot), trust_remote_code=True, local_files_only=True,
        codec_weight_dtype=precision, low_cpu_mem_usage=True,
    ).eval().cuda()
    model.set_attention_implementation(backend)
    model.set_compute_dtype(precision)
    return model


def demo_codes(model, snapshot):
    waveform, input_rate = sf.read(snapshot / "demo/demo_gt.wav", dtype="float32", always_2d=True)
    source = torch.from_numpy(waveform.T.copy()).unsqueeze(0)
    source = F.interpolate(
        source, size=round(source.shape[-1] * SAMPLE_RATE / input_rate),
        mode="linear", align_corners=False,
    )
    if source.shape[1] == 1:
        source = source.repeat(1, 2, 1)
    samples = TOTAL_FRAMES * SAMPLES_PER_FRAME
    stereo = source.repeat(1, 1, math.ceil(samples / source.shape[-1]))[:, :, :samples]
    codes = model.encode(stereo.contiguous().cuda(), return_dict=True).audio_codes
    assert tuple(codes.shape) == (32, 1, TOTAL_FRAMES), codes.shape
    return codes


def audio(output, expected_samples):
    assert output.audio.shape[-1] == expected_samples, output.audio.shape
    return output.audio


def compare(actual, reference):
    assert actual.shape == reference.shape, (actual.shape, reference.shape)
    actual, reference = actual.double(), reference.double()
    difference = actual - reference
    rmse = difference.square().mean().sqrt().item()
    signal_rms = reference.square().mean().sqrt().item()
    return {
        "samples_per_channel": actual.shape[-1],
        "exact": torch.equal(actual, reference),
        "finite": bool(torch.isfinite(actual).all().item()),
        "peak": difference.abs().max().item(),
        "rmse": rmse,
        "normalized_rmse": rmse / signal_rms,
        "snr_db": 20 * math.log10(signal_rms / rmse) if rmse else None,
    }


def stream(model, codes, chunk_frames, mode="private", measure=False):
    outputs = []
    timings = []
    decoder = model.decode if mode == "public" else model._decode_frame
    with model.streaming(batch_size=codes.shape[1]):
        if measure:
            torch.cuda.synchronize()
        for step in codes.split(chunk_frames, dim=-1):
            if measure:
                start = time.perf_counter_ns()
            out = decoder(step, return_dict=True) if mode == "public" else decoder(step)
            if measure:
                torch.cuda.synchronize()
                timings.append((time.perf_counter_ns() - start) / 1e6)
            outputs.append(audio(out, step.shape[-1] * SAMPLES_PER_FRAME))
    return torch.cat(outputs, dim=-1), timings


def stage_state(model):
    return [
        [layer.self_attn._streaming_state for layer in module.transformer.layers]
        for module in model.decoder
        if hasattr(module, "transformer")
    ]


def measure_state(model, codes):
    stages = []
    with model.streaming(batch_size=1):
        for step in codes.split(16, dim=-1):
            model._decode_frame(step)
        for stage, states in enumerate(stage_state(model)):
            state = states[0]
            cache_bytes = sum(
                tensor.numel() * tensor.element_size()
                for layer in states
                for tensor in (layer.cached_keys, layer.cached_values, layer.cached_positions)
            )
            stages.append({
                "number": stage + 1,
                "layers": len(states),
                "rate_hz": SAMPLE_RATE / SAMPLES_PER_FRAME * (2 ** stage),
                "keys_shape": list(state.cached_keys.shape),
                "cache_dtype": str(state.cached_keys.dtype),
                "cache_positions_first_last": [
                    state.cached_positions[0, 0].item(), state.cached_positions[0, -1].item(),
                ],
                "final_offset": state.offset[0].item(),
                "persistent_kvp_bytes": cache_bytes,
            })
    return stages


def profile_sdpa(model, codes):
    with model.streaming(batch_size=1):
        model._decode_frame(codes[:, :, :4])
        with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU]) as profile:
            model._decode_frame(codes[:, :, 4:8])
            torch.cuda.synchronize()
    return sorted({
        entry.key for entry in profile.key_averages() if "scaled_dot_product" in entry.key
    })


def reset_negative_controls(model, codes, reference, chunk_frames):
    short = codes[:, :, : 6 * chunk_frames].contiguous()
    ref = reference[:, :, : short.shape[-1] * SAMPLES_PER_FRAME]
    first_samples = chunk_frames * SAMPLES_PER_FRAME
    reset = torch.cat([
        model.decode(step, return_dict=True).audio for step in short.split(chunk_frames, dim=-1)
    ], dim=-1)
    result = {
        "fresh_contexts": compare(reset[:, :, first_samples:], ref[:, :, first_samples:]),
    }
    for control in ("zero_attention_offsets_only", "clear_kv_history_only"):
        outputs = []
        with model.streaming(batch_size=1):
            for index, step in enumerate(short.split(chunk_frames, dim=-1)):
                if index:
                    for states in stage_state(model):
                        for state in states:
                            if control == "zero_attention_offsets_only":
                                state.offset.zero_()
                            else:
                                state.cached_keys.zero_()
                                state.cached_values.zero_()
                                state.cached_positions.fill_(-1)
                outputs.append(model._decode_frame(step).audio)
        ablated = torch.cat(outputs, dim=-1)
        result[control] = compare(ablated[:, :, first_samples:], ref[:, :, first_samples:])
    return result


def snapshot_resume(model, codes):
    prefix, suffix = codes[:, :, :12], codes[:, :, 12:16]
    with model.streaming(batch_size=1):
        model._decode_frame(prefix)
        states = {
            name: deepcopy(module._streaming_state)
            for name, module in model.decoder.named_modules()
            if getattr(module, "_streaming_state", None) is not None
        }
        uninterrupted = model._decode_frame(suffix).audio
    with model.streaming(batch_size=1):
        for name, module in model.decoder.named_modules():
            if name in states:
                module._streaming_state = states[name]
        restored = model._decode_frame(suffix).audio
    return compare(restored, uninterrupted)


def ragged_lanes(model, codes, reference):
    chunk_frames = 4
    short_frames = chunk_frames * 2
    other = codes[:, :, 37:37 + short_frames].contiguous()
    other_ref = model.decode(other, return_dict=True).audio
    outputs = [[], []]

    def pair(a, b):
        return torch.cat((a, b), dim=1).contiguous()

    steps = [
        ((True, True), pair(codes[:, :, :4], other[:, :, :4])),
        ((True, False), pair(codes[:, :, 4:8], torch.zeros_like(other[:, :, :4]))),
        ((True, True), pair(codes[:, :, 8:12], other[:, :, 4:8])),
    ]
    frozen = None
    with model.streaming(batch_size=2):
        for index, (enabled, frame_pair) in enumerate(steps):
            mask = torch.tensor(enabled, device=codes.device, dtype=torch.bool)
            lengths = mask.long() * chunk_frames
            model._set_streaming_exec_mask(mask)
            result = model._decode_frame(frame_pair, lengths)
            states = [state for stage in stage_state(model) for state in stage]
            tensors = [tensor for s in states for tensor in (s.cached_keys, s.cached_values, s.cached_positions, s.offset)]
            if index == 0:
                frozen = [tensor[1].clone() for tensor in tensors]
            elif index == 1:
                unchanged = all(torch.equal(tensor[1], stored) for tensor, stored in zip(tensors, frozen, strict=True))
                assert result.audio_lengths[1].item() == 0
            for slot, active in enumerate(enabled):
                if active:
                    assert result.audio_lengths[slot].item() == chunk_frames * SAMPLES_PER_FRAME
                    outputs[slot].append(result.audio[slot:slot + 1])
    return {
        "paused_lane_state_exact": unchanged,
        "active_lane_error": compare(torch.cat(outputs[0], dim=-1), reference[:, :, :12 * SAMPLES_PER_FRAME]),
        "resumed_lane_error": compare(torch.cat(outputs[1], dim=-1), other_ref),
    }


def run_causality_checks(model, codes, reference):
    prefix_frames = 37
    prefix_samples = prefix_frames * SAMPLES_PER_FRAME
    replacement = torch.Generator(device="cpu").manual_seed(20261125)
    perturbed = codes.clone()
    perturbed[:, :, prefix_frames:] = torch.randint(
        model.config.quantizer_kwargs["codebook_size"],
        perturbed[:, :, prefix_frames:].shape, generator=replacement,
    ).cuda()
    perturbed_out = model.decode(perturbed, return_dict=True).audio
    prefix_out = model.decode(codes[:, :, :prefix_frames], return_dict=True).audio
    return {
        "prefix_frames": prefix_frames,
        "future_mutation_prefix": compare(perturbed_out[:, :, :prefix_samples], reference[:, :, :prefix_samples]),
        "future_mutation_changed_suffix": compare(perturbed_out[:, :, prefix_samples:], reference[:, :, prefix_samples:]),
        "truncated_prefix": compare(prefix_out, reference[:, :, :prefix_samples]),
    }


def benchmark_stream(model, codes, reference, chunk_frames, repetitions, mode="private"):
    # Warm the exact chunk shape once, with a disposable context. Each timed pass owns a fresh context.
    stream(model, codes[:, :, :chunk_frames], chunk_frames, mode=mode)
    first = []
    steady = []
    partial = []
    total = []
    for _ in range(repetitions):
        streamed, timing = stream(model, codes, chunk_frames, mode=mode, measure=True)
        first.append(timing[0])
        last_full = len(timing) if codes.shape[-1] % chunk_frames == 0 else len(timing) - 1
        steady.extend(timing[1:last_full])
        partial.extend(timing[last_full:])
        total.append(sum(timing))
    chunk_ms = chunk_frames * SAMPLES_PER_FRAME / SAMPLE_RATE * 1e3
    clip_ms = codes.shape[-1] * SAMPLES_PER_FRAME / SAMPLE_RATE * 1e3
    median = statistics.median(steady)
    return {
        "chunk_frames": chunk_frames,
        "chunk_ms": chunk_ms,
        "first_chunk_wall_ms": first,
        "steady_wall_p50_ms": median,
        "steady_wall_p95_ms": float(np.percentile(steady, 95)),
        "steady_wall_max_ms": max(steady),
        "steady_full_chunks": len(steady),
        "partial_final_chunk_wall_ms": partial,
        "session_decode_wall_ms": total,
        "throughput_x": clip_ms / statistics.median(total),
        "steady_chunk_budget_over_p50_x": chunk_ms / median,
        "steady_full_chunks_over_budget": sum(value > chunk_ms for value in steady),
        "steady_full_chunk_wall_ms": steady,
        "error": compare(streamed, reference),
    }


def write_report(path, result):
    path.write_text(json.dumps(result, indent=2, allow_nan=False) + "\n")


def run_public_cross_check(snapshot, output):
    result = json.loads(output.read_text())
    backend = result["backend"]
    if result["revision"] != REVISION:
        raise ValueError("Existing results were collected on a different checkpoint revision")
    fp32_single = next(row for row in result["fp32"]["streaming"] if row["chunk_frames"] == 1)
    fp32_chunk = 1 if fp32_single["steady_full_chunks_over_budget"] == 0 and fp32_single["throughput_x"] >= 1 else 4
    rows = []
    for precision, chunk_frames in (("bf16", 2), ("fp32", fp32_chunk)):
        model = load_model(snapshot, precision, backend if precision == "bf16" else "sdpa")
        if precision == "bf16":
            codes = demo_codes(model, snapshot)
        reference = model.decode(codes, return_dict=True).audio
        row = benchmark_stream(model, codes, reference, chunk_frames, 1, mode="public")
        row["precision"] = precision
        rows.append(row)
        result["public_cross_check"] = rows
        write_report(output, result)
        print(
            f"{precision.upper()} public {chunk_frames} frames: {row['throughput_x']:.2f}x, "
            f"steady p50 {row['steady_wall_p50_ms']:.2f} ms", flush=True,
        )
        del model
        torch.cuda.empty_cache()


@torch.inference_mode()
def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--snapshot", type=Path)
    parser.add_argument("--output", type=Path, default=Path("causal_results.json"))
    parser.add_argument("--repetitions", type=int, default=3)
    parser.add_argument("--backend", choices=["sdpa", "flash_attention_2"], default="sdpa")
    parser.add_argument("--skip-fp32", action="store_true")
    parser.add_argument("--public-cross-check", action="store_true", help="append one live public-API session per precision")
    args = parser.parse_args()
    if args.repetitions < 1:
        parser.error("--repetitions must be positive")
    torch.set_num_threads(4)
    torch.backends.cuda.matmul.fp32_precision = "ieee"
    torch.backends.cudnn.conv.fp32_precision = "ieee"
    snapshot = args.snapshot or Path(snapshot_download(REPO, revision=REVISION))
    if args.public_cross_check:
        run_public_cross_check(snapshot, args.output)
        return
    result = {
        "repo": REPO, "revision": REVISION,
        "torch": str(torch.__version__), "torch_cuda": torch.version.cuda,
        "transformers": transformers.__version__, "gpu": torch.cuda.get_device_name(),
        "backend": args.backend,
        "waveform": "Pinned HF demo_gt.wav, mono 24 kHz, linearly resampled to 48 kHz, duplicated to stereo, repeated then truncated",
        "frames": TOTAL_FRAMES, "sample_rate": SAMPLE_RATE, "samples_per_frame": SAMPLES_PER_FRAME,
        "codebooks": 32, "duration_s": TOTAL_FRAMES * SAMPLES_PER_FRAME / SAMPLE_RATE,
        "repetitions": args.repetitions, "host_cpu_threads": torch.get_num_threads(),
    }
    model = load_model(snapshot, "bf16", args.backend)
    attention = next(module for module in model.decoder.modules() if hasattr(module, "_forward_streaming_sdpa"))
    actual_backend = attention.resolve_attention_implementation(torch.empty(1, dtype=torch.bfloat16, device="cuda"), True)
    if args.backend != actual_backend:
        raise RuntimeError(f"Requested {args.backend}; model resolved {actual_backend}")
    result["dtype"] = model.get_codec_dtype_summary()
    codes = demo_codes(model, snapshot)
    reference = audio(model.decode(codes, return_dict=True), TOTAL_FRAMES * SAMPLES_PER_FRAME)
    result["checks"] = run_causality_checks(model, codes, reference)
    result["streaming"] = []
    for chunk_frames in CHUNK_SIZES:
        row = benchmark_stream(model, codes, reference, chunk_frames, args.repetitions)
        result["streaming"].append(row)
        write_report(args.output, result)
        print(
            f"BF16 {chunk_frames} frames: {row['throughput_x']:.2f}x, "
            f"steady p50 {row['steady_wall_p50_ms']:.2f} ms, "
            f"reference RMSE {row['error']['rmse']:.3g}",
            flush=True,
        )
    print("Running public API, cache and negative controls", flush=True)
    result["checks"]["public_offline_chunked_vs_full"] = compare(
        model.decode(codes, chunk_duration=.32, return_dict=True).audio, reference,
    )
    public, _ = stream(model, codes, 4, mode="public")
    result["checks"]["public_live_vs_full"] = compare(public, reference)
    result["checks"]["public_live_vs_public_offline_chunked"] = compare(
        public, model.decode(codes, chunk_duration=.32, return_dict=True).audio,
    )
    result["checks"].update(reset_negative_controls(model, codes, reference, 4))
    result["checks"]["ragged_lanes"] = ragged_lanes(model, codes, reference)
    result["checks"]["snapshot_resume"] = snapshot_resume(model, codes)
    result["stages"] = measure_state(model, codes)
    result["sdpa_ops_for_four_frame_step"] = profile_sdpa(model, codes)
    write_report(args.output, result)
    del attention
    del model
    torch.cuda.empty_cache()

    if not args.skip_fp32:
        print("Running FP32, using the same code input", flush=True)
        model = load_model(snapshot, "fp32", "sdpa")
        fp32_ref = model.decode(codes, return_dict=True).audio
        result["fp32"] = {
            "backend": "sdpa", "dtype": model.get_codec_dtype_summary(), "tf32_enabled": False,
            **run_causality_checks(model, codes, fp32_ref),
            "streaming": [],
        }
        for chunk_frames in (1, 4):
            row = benchmark_stream(model, codes, fp32_ref, chunk_frames, args.repetitions)
            result["fp32"]["streaming"].append(row)
            write_report(args.output, result)
            print(
                f"FP32 {chunk_frames} frames: {row['throughput_x']:.2f}x, "
                f"steady p50 {row['steady_wall_p50_ms']:.2f} ms, "
                f"reference RMSE {row['error']['rmse']:.3g}",
                flush=True,
            )
    print(f"Wrote {args.output}", flush=True)


if __name__ == "__main__":
    main()
