#![allow(
    clippy::assertions_on_constants,
    clippy::assertions_on_result_states,
    clippy::clone_on_copy,
    clippy::decimal_literal_representation,
    clippy::doc_markdown,
    clippy::empty_line_after_doc_comments,
    clippy::field_reassign_with_default,
    clippy::get_unwrap,
    clippy::identity_op,
    clippy::inconsistent_digit_grouping,
    clippy::indexing_slicing,
    clippy::integer_division,
    clippy::len_zero,
    clippy::let_underscore_must_use,
    clippy::manual_div_ceil,
    clippy::manual_let_else,
    clippy::manual_range_contains,
    clippy::modulo_arithmetic,
    clippy::needless_range_loop,
    clippy::non_ascii_literal,
    clippy::redundant_clone,
    clippy::shadow_reuse,
    clippy::shadow_same,
    clippy::shadow_unrelated,
    clippy::single_match_else,
    clippy::str_to_string,
    clippy::string_slice,
    clippy::tests_outside_test_module,
    clippy::too_many_lines,
    clippy::unnecessary_wraps,
    clippy::unseparated_literal_suffix,
    clippy::use_debug,
    clippy::useless_vec,
    clippy::wildcard_enum_match_arm,
    clippy::else_if_without_else,
    clippy::expect_used,
    clippy::missing_const_for_fn,
    clippy::similar_names,
    clippy::type_complexity,
    clippy::collapsible_else_if,
    clippy::doc_lazy_continuation,
    clippy::items_after_test_module,
    clippy::map_clone,
    clippy::multiple_unsafe_ops_per_block,
    clippy::unwrap_or_default,
    clippy::assign_op_pattern,
    clippy::needless_borrow,
    clippy::println_empty_string,
    clippy::unnecessary_cast,
    clippy::used_underscore_binding,
    clippy::create_dir,
    clippy::implicit_saturating_sub,
    clippy::exit,
    clippy::expect_fun_call,
    clippy::too_many_arguments,
    clippy::unnecessary_map_or,
    clippy::unwrap_used,
    dead_code,
    unused_imports,
    unused_variables,
    clippy::cloned_ref_to_slice_refs,
    clippy::neg_multiply,
    clippy::while_let_loop,
    clippy::bool_assert_comparison,
    clippy::excessive_precision,
    clippy::trivially_copy_pass_by_ref,
    clippy::op_ref,
    clippy::redundant_closure,
    clippy::unnecessary_lazy_evaluations,
    clippy::if_then_some_else_none,
    clippy::unnecessary_to_owned,
    clippy::single_component_path_imports,
)]
//! Simplified test to verify dtype conversion hypothesis.
//!
//! Post-migration: GpuTensor is ALWAYS f32 (no dtype dispatch). The original
//! Candle-era tests checked DType::F32 on network output and gather operations.
//! Since the entire pipeline is now natively f32, these tests verify that the
//! DistributionalDuelingQNetwork produces valid, finite output with correct shapes.

use ml::dqn::{DistributionalDuelingConfig, DistributionalDuelingQNetwork};
use ml::MLError;
use ml_core::cuda_autograd::GpuTensor;
use ml_core::device::MlDevice;
use std::sync::Arc;
use tracing::info;

/// Get a shared CUDA stream for tests.
fn cuda_stream() -> Arc<cudarc::driver::CudaStream> {
    let device = MlDevice::cuda(0).expect("CUDA device required");
    Arc::clone(device.cuda_stream().expect("CUDA stream required"))
}

#[test]
fn test_network_outputs_f32_naturally() -> Result<(), MLError> {
    let stream = cuda_stream();

    info!("Testing Network Output (always f32 in GPU-native pipeline)");

    // Create network config matching production
    let config = DistributionalDuelingConfig {
        state_dim: 54,
        num_actions: 45,
        num_atoms: 51,
        shared_hidden_dims: vec![256, 128],
        value_hidden_dim: 128,
        advantage_hidden_dim: 128,
        leaky_relu_alpha: 0.01,
    };

    let network = DistributionalDuelingQNetwork::new(config, Arc::clone(&stream))?;

    // Create f32 input [batch=32, state_dim=54]
    let input_data = vec![0.0f32; 32 * 54];
    let input_tensor = GpuTensor::from_host(&input_data, vec![32, 54], &stream)?;

    info!(shape = ?input_tensor.shape(), "Input shape");

    // Forward pass
    let output = network.forward(&input_tensor)?;

    info!(shape = ?output.shape(), "Output shape");

    // Expected output shape: [batch, actions, atoms] = [32, 45, 51]
    let expected_shape: &[usize] = &[32, 45, 51];
    assert_eq!(
        output.shape(),
        expected_shape,
        "Output shape mismatch"
    );

    // GpuTensor is ALWAYS f32 -- no dtype check needed.
    // Verify output is finite (no NaN/Inf from the forward pass).
    let output_host = output.to_host(&stream)?;
    let all_finite = output_host.iter().all(|v| v.is_finite());
    assert!(all_finite, "Network output contains NaN or Inf values");

    info!("Network outputs f32 natively; no dtype conversion needed");

    // Verify gather-like operation: extract action 0's atom distribution for each batch sample
    // In the native pipeline, gather is done by narrow/reshape on the flat host data.
    info!("Testing action selection (narrow operation)");

    // Narrow along dim=1 (actions): take action 0 -> [32, 1, 51]
    let gathered = output.narrow(1, 0, 1, &stream)?;
    // Squeeze dim=1 -> [32, 51]
    let squeezed = gathered.squeeze(1, &stream)?;

    info!(shape = ?squeezed.shape(), "After narrow+squeeze");

    assert_eq!(
        squeezed.shape(),
        &[32, 51],
        "Gathered shape mismatch after narrow+squeeze"
    );

    // Verify gathered values are finite
    let gathered_host = squeezed.to_host(&stream)?;
    let all_gathered_finite = gathered_host.iter().all(|v| v.is_finite());
    assert!(all_gathered_finite, "Gathered output contains NaN or Inf values");

    info!("Gather (narrow+squeeze) preserves f32; no dtype conversion needed");

    Ok(())
}

#[test]
fn test_if_dtype_conversion_line_1087_is_necessary() -> Result<(), MLError> {
    let stream = cuda_stream();

    info!("Analyzing Line 1087: to_dtype is a no-op in GPU-native pipeline (always f32)");

    // Recreate exact code path from dqn.rs lines 1079-1087
    let config = DistributionalDuelingConfig {
        state_dim: 54,
        num_actions: 45,
        num_atoms: 51,
        shared_hidden_dims: vec![256, 128],
        value_hidden_dim: 128,
        advantage_hidden_dim: 128,
        leaky_relu_alpha: 0.01,
    };

    let network = DistributionalDuelingQNetwork::new(config, Arc::clone(&stream))?;

    let states = vec![0.0f32; 32 * 54];
    let state_tensor = GpuTensor::from_host(&states, vec![32, 54], &stream)?;

    // Line 1079: let q_dists = self.dist_dueling_q_network.forward(&states_tensor)?;
    let q_dists = network.forward(&state_tensor)?;
    info!(shape = ?q_dists.shape(), "Line 1079 q_dists shape (always f32)");

    // Lines 1084-1086: gather action 0, squeeze
    // In the native pipeline, gather is replaced by narrow+squeeze
    let state_action_values_before_conversion = q_dists
        .narrow(1, 0, 1, &stream)?
        .squeeze(1, &stream)?;

    info!(shape = ?state_action_values_before_conversion.shape(), "Lines 1084-1086 shape");

    // Line 1087: .to_dtype(DType::F32)? -- in native pipeline this is GpuTensor::to_dtype
    // which is always a no-op clone since GpuTensor is always f32.
    let state_action_values_after_conversion = state_action_values_before_conversion
        .to_dtype(ml_core::native_types::NativeDType::F32, &stream)?;

    info!(shape = ?state_action_values_after_conversion.shape(), "Line 1087 after to_dtype");

    // VERDICT: In the GPU-native pipeline, GpuTensor is always f32.
    // The to_dtype call is a no-op (shallow clone). No risk of gradient breakage
    // because there is no autograd tape to break -- gradients are computed via
    // explicit backward kernels.
    info!("VERDICT: Line 1087 to_dtype is a no-op in GPU-native pipeline (GpuTensor is always f32)");

    // Verify the values are identical (no data corruption from the no-op cast)
    let before = state_action_values_before_conversion.to_host(&stream)?;
    let after = state_action_values_after_conversion.to_host(&stream)?;
    assert_eq!(before.len(), after.len(), "Length mismatch after to_dtype");

    let max_diff = before.iter().zip(after.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0_f32, f32::max);

    assert!(
        max_diff < 1e-7,
        "to_dtype should be a no-op, max_diff={}",
        max_diff
    );

    Ok(())
}
