#![allow(unsafe_code)] // Required for CUDA kernel launch

//! Signal adapter utilities for converting between model outputs and action scores.
//!
//! Pure cudarc `CudaSlice<f32>` operations -- zero Candle Tensor usage.
//! Three CUDA kernels bridge the gap between model predictions and the 5-action
//! DQN exposure space (Short100, Short50, Flat, Long50, Long100).

use cudarc::driver::{CudaContext, CudaFunction, CudaSlice, CudaStream, LaunchConfig, PushKernelArg};
use std::sync::Arc;

use crate::MLError;

/// Precompiled signal_adapter kernel cubin, embedded at compile time by build.rs.
static SIGNAL_ADAPTER_CUBIN: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/signal_adapter_kernel.cubin"));

/// Kernel handle set for signal adapter operations.
struct KernelSet {
    ppo_exposure: CudaFunction,
    signal_to_action: CudaFunction,
    tft_extract: CudaFunction,
}

fn load_kernels(context: &Arc<CudaContext>) -> Result<KernelSet, MLError> {
    let module = context
        .load_cubin(SIGNAL_ADAPTER_CUBIN.to_vec())
        .map_err(|e| MLError::ModelError(format!("signal_adapter module load: {e}")))?;

    let ppo_exposure = module
        .load_function("ppo_to_exposure_scores_kernel")
        .map_err(|e| MLError::ModelError(format!("ppo_to_exposure_scores_kernel load: {e}")))?;
    let signal_to_action = module
        .load_function("signal_to_action_scores_kernel")
        .map_err(|e| MLError::ModelError(format!("signal_to_action_scores_kernel load: {e}")))?;
    let tft_extract = module
        .load_function("tft_quantile_extract_kernel")
        .map_err(|e| MLError::ModelError(format!("tft_quantile_extract_kernel load: {e}")))?;

    Ok(KernelSet { ppo_exposure, signal_to_action, tft_extract })
}

// ── Public API ──────────────────────────────────────────────────────────

/// Aggregate PPO 63-action softmax probabilities into 7 exposure scores.
///
/// PPO uses a 63-action factored space (7 exposure x 3 order x 3 urgency).
/// This collapses the order/urgency dimensions to produce a `[batch * 7]`
/// `CudaSlice` whose per-row argmax gives the dominant exposure bucket.
///
/// # Arguments
/// * `probs` - GPU-resident `[batch * 63]` softmax probabilities
/// * `batch` - number of rows
/// * `stream` - CUDA stream for kernel launch and allocation
///
/// # Returns
/// GPU-resident `CudaSlice<f32>` of shape `[batch * 7]`.
///
/// # Errors
/// Returns `MLError::ModelError` on kernel compilation or launch failure.
pub fn ppo_to_exposure_scores(
    probs: &CudaSlice<f32>,
    batch: usize,
    stream: &Arc<CudaStream>,
) -> Result<CudaSlice<f32>, MLError> {
    let context = stream.context();
    let kernels = load_kernels(&context)?;

    let mut out = stream
        .alloc_zeros::<f32>(batch * 7)
        .map_err(|e| MLError::ModelError(format!("alloc exposure scores: {e}")))?;

    let batch_i32 = batch as i32;
    let grid = ((batch as u32 + 255) / 256).max(1);
    let cfg = LaunchConfig {
        grid_dim: (grid, 1, 1),
        block_dim: (256, 1, 1),
        shared_mem_bytes: 0,
    };

    // Safety: argument order matches ppo_to_exposure_scores_kernel(probs, out, batch)
    unsafe {
        stream
            .launch_builder(&kernels.ppo_exposure)
            .arg(probs)
            .arg(&mut out)
            .arg(&batch_i32)
            .launch(cfg)
            .map_err(|e| MLError::ModelError(format!("ppo_to_exposure_scores launch: {e}")))?;
    }

    Ok(out)
}

/// Map scalar return predictions (bps) to 7-action one-hot-ish scores.
///
/// Thresholds partition the real line into bins matching the 7-level
/// ExposureLevel enum:
/// - `pred < -high`           => ShortFull  (action 2)
/// - `-high <= pred < -low`   => ShortHalf  (action 1)
/// - `-low  <= pred <= +low`  => Flat       (action 3)
/// - `+low  <  pred <= +high` => LongHalf   (action 5)
/// - `pred  >  +high`         => LongFull   (action 6)
///
/// # Arguments
/// * `predictions` - GPU-resident `[batch]` scalar signals
/// * `batch` - number of elements
/// * `high_threshold_bps` - strong signal threshold
/// * `low_threshold_bps` - mild signal threshold
/// * `stream` - CUDA stream for kernel launch and allocation
///
/// # Returns
/// GPU-resident `CudaSlice<f32>` of shape `[batch * 7]` (one-hot rows).
///
/// # Errors
/// Returns `MLError::ModelError` on kernel compilation or launch failure.
pub fn signal_to_action_scores(
    predictions: &CudaSlice<f32>,
    batch: usize,
    high_threshold_bps: f32,
    low_threshold_bps: f32,
    stream: &Arc<CudaStream>,
) -> Result<CudaSlice<f32>, MLError> {
    let context = stream.context();
    let kernels = load_kernels(&context)?;

    let mut out = stream
        .alloc_zeros::<f32>(batch * 7)
        .map_err(|e| MLError::ModelError(format!("alloc action scores: {e}")))?;

    let batch_i32 = batch as i32;
    let grid = ((batch as u32 + 255) / 256).max(1);
    let cfg = LaunchConfig {
        grid_dim: (grid, 1, 1),
        block_dim: (256, 1, 1),
        shared_mem_bytes: 0,
    };

    // Safety: argument order matches signal_to_action_scores_kernel(
    //   predictions, out_scores, high_threshold_bps, low_threshold_bps, batch)
    unsafe {
        stream
            .launch_builder(&kernels.signal_to_action)
            .arg(predictions)
            .arg(&mut out)
            .arg(&high_threshold_bps)
            .arg(&low_threshold_bps)
            .arg(&batch_i32)
            .launch(cfg)
            .map_err(|e| MLError::ModelError(format!("signal_to_action_scores launch: {e}")))?;
    }

    Ok(out)
}

/// Extract the median signal from TFT quantile predictions.
///
/// Input layout: `[batch * horizon * num_quantiles]` (typically `[batch * 1 * 3]`).
/// Returns `[batch]` -- the median (quantile index 1) from the first horizon step.
///
/// # Arguments
/// * `quantiles` - GPU-resident `[batch * horizon * num_quantiles]` data
/// * `batch` - batch size
/// * `horizon` - number of horizon steps (>= 1)
/// * `num_quantiles` - number of quantiles (>= 2, median at index 1)
/// * `stream` - CUDA stream for kernel launch and allocation
///
/// # Returns
/// GPU-resident `CudaSlice<f32>` of shape `[batch]`.
///
/// # Errors
/// Returns `MLError::ModelError` if dimensions are invalid or kernel fails.
pub fn tft_quantile_to_signal(
    quantiles: &CudaSlice<f32>,
    batch: usize,
    horizon: usize,
    num_quantiles: usize,
    stream: &Arc<CudaStream>,
) -> Result<CudaSlice<f32>, MLError> {
    if horizon < 1 {
        return Err(MLError::ModelError(
            "tft_quantile_to_signal: horizon must be >= 1".to_owned(),
        ));
    }
    if num_quantiles < 2 {
        return Err(MLError::ModelError(format!(
            "tft_quantile_to_signal: need >= 2 quantiles, got {num_quantiles}"
        )));
    }

    let context = stream.context();
    let kernels = load_kernels(&context)?;

    let mut out = stream
        .alloc_zeros::<f32>(batch)
        .map_err(|e| MLError::ModelError(format!("alloc tft signal: {e}")))?;

    let batch_i32 = batch as i32;
    let horizon_i32 = horizon as i32;
    let num_q_i32 = num_quantiles as i32;
    let grid = ((batch as u32 + 255) / 256).max(1);
    let cfg = LaunchConfig {
        grid_dim: (grid, 1, 1),
        block_dim: (256, 1, 1),
        shared_mem_bytes: 0,
    };

    // Safety: argument order matches tft_quantile_extract_kernel(
    //   quantiles, out_signal, horizon, num_quantiles, batch)
    unsafe {
        stream
            .launch_builder(&kernels.tft_extract)
            .arg(quantiles)
            .arg(&mut out)
            .arg(&horizon_i32)
            .arg(&num_q_i32)
            .arg(&batch_i32)
            .launch(cfg)
            .map_err(|e| MLError::ModelError(format!("tft_quantile_extract launch: {e}")))?;
    }

    Ok(out)
}

/// Compute walk-forward backtest fitness for hyperopt (minimization).
///
/// - `trades >= min_trades`: return `-sharpe` (lower is better for minimizers)
/// - `0 < trades < min_trades`: return `-sharpe * (trades / min_trades)` (penalty)
/// - `trades == 0`: return `1.0 / (1.0 + threshold_distance)` (always positive,
///   guides the optimizer toward viable threshold regions)
pub fn backtest_fitness(
    sharpe: f32,
    total_trades: u32,
    min_trades: u32,
    threshold_distance: f32,
) -> f64 {
    if total_trades == 0 {
        return 1.0 / (1.0 + threshold_distance as f64);
    }
    let s = -(sharpe as f64);
    if total_trades >= min_trades {
        s
    } else {
        s * (total_trades as f64 / min_trades as f64)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cuda_stream() -> Arc<CudaStream> {
        let context = cudarc::driver::CudaContext::new(0).expect("CUDA context required");
        context.default_stream()
    }

    // ── ppo_to_exposure_scores ──────────────────────────────────────────

    #[test]
    fn test_ppo_to_exposure_scores_shape() {
        let stream = cuda_stream();
        let batch = 4;
        let uniform = vec![1.0_f32 / 63.0; batch * 63];
        let mut probs_buf = stream.alloc_zeros::<f32>(batch * 63).unwrap();
        stream.memcpy_htod(&uniform, &mut probs_buf).unwrap();

        let scores = ppo_to_exposure_scores(&probs_buf, batch, &stream).unwrap();

        // Download and check shape + values
        let mut host = vec![0.0_f32; batch * 7];
        stream.memcpy_dtoh(&scores, &mut host).unwrap();
        stream.synchronize().unwrap();

        assert_eq!(host.len(), batch * 7);
        // Each of 7 bins sums 9 cells of 1/63 ≈ 0.1429
        let expected = 9.0 / 63.0;
        for val in &host {
            assert!(
                (*val - expected).abs() < 0.01,
                "expected ~{expected} everywhere, got {val}"
            );
        }
    }

    #[test]
    fn test_ppo_to_exposure_scores_argmax() {
        let stream = cuda_stream();
        // Put all mass on actions 54..62 => exposure bin 6 (LongFull)
        let batch = 2;
        let mut raw = vec![0.0_f32; batch * 63];
        for b in 0..batch {
            for a in 54..63 {
                if let Some(slot) = raw.get_mut(b * 63 + a) {
                    *slot = 1.0 / 9.0;
                }
            }
        }
        let mut probs_buf = stream.alloc_zeros::<f32>(batch * 63).unwrap();
        stream.memcpy_htod(&raw, &mut probs_buf).unwrap();

        let scores = ppo_to_exposure_scores(&probs_buf, batch, &stream).unwrap();
        let mut host = vec![0.0_f32; batch * 7];
        stream.memcpy_dtoh(&scores, &mut host).unwrap();
        stream.synchronize().unwrap();

        // Each row should have argmax at index 6 (LongFull)
        for b in 0..batch {
            let row_start = b * 7;
            let mut best_idx = 0;
            let mut best_val = f32::NEG_INFINITY;
            for i in 0..7 {
                let v = host[row_start + i];
                if v > best_val {
                    best_val = v;
                    best_idx = i;
                }
            }
            assert_eq!(best_idx, 6, "batch {b}: expected argmax=6 (LongFull), got {best_idx}");
        }
    }

    // ── signal_to_action_scores ─────────────────────────────────────────

    /// Host-side argmax over a [1, 7] row downloaded from GPU.
    fn host_argmax(host: &[f32]) -> usize {
        let mut best_idx = 0;
        let mut best_val = f32::NEG_INFINITY;
        for (i, &v) in host.iter().enumerate() {
            if v > best_val {
                best_val = v;
                best_idx = i;
            }
        }
        best_idx
    }

    fn run_signal_test(pred_val: f32, high: f32, low: f32) -> Vec<f32> {
        let stream = cuda_stream();
        let pred = [pred_val];
        let mut pred_buf = stream.alloc_zeros::<f32>(1).unwrap();
        stream.memcpy_htod(&pred, &mut pred_buf).unwrap();
        let scores = signal_to_action_scores(&pred_buf, 1, high, low, &stream).unwrap();
        let mut host = vec![0.0_f32; 7];
        stream.memcpy_dtoh(&scores, &mut host).unwrap();
        stream.synchronize().unwrap();
        host
    }

    #[test]
    fn test_signal_to_action_scores_strong_long() {
        let host = run_signal_test(20.0, 10.0, 5.0);
        assert_eq!(host_argmax(&host), 6); // LongFull
    }

    #[test]
    fn test_signal_to_action_scores_strong_short() {
        let host = run_signal_test(-20.0, 10.0, 5.0);
        assert_eq!(host_argmax(&host), 2); // ShortFull
    }

    #[test]
    fn test_signal_to_action_scores_flat() {
        let host = run_signal_test(0.0, 10.0, 5.0);
        assert_eq!(host_argmax(&host), 3); // Flat
    }

    #[test]
    fn test_signal_to_action_scores_mild_long() {
        let host = run_signal_test(7.0, 10.0, 5.0);
        assert_eq!(host_argmax(&host), 5); // LongHalf
    }

    #[test]
    fn test_signal_to_action_scores_mild_short() {
        let host = run_signal_test(-7.0, 10.0, 5.0);
        assert_eq!(host_argmax(&host), 1); // ShortHalf
    }

    // ── tft_quantile_to_signal ──────────────────────────────────────────

    #[test]
    fn test_tft_quantile_to_signal() {
        let stream = cuda_stream();
        // [batch=2, horizon=1, quantiles=3]
        let data: Vec<f32> = vec![
            -1.0, 0.5, 2.0,   // batch 0: median = 0.5
            -3.0, -1.5, 0.0,  // batch 1: median = -1.5
        ];
        let mut q_buf = stream.alloc_zeros::<f32>(data.len()).unwrap();
        stream.memcpy_htod(&data, &mut q_buf).unwrap();

        let signal = tft_quantile_to_signal(&q_buf, 2, 1, 3, &stream).unwrap();
        let mut host = vec![0.0_f32; 2];
        stream.memcpy_dtoh(&signal, &mut host).unwrap();
        stream.synchronize().unwrap();

        // f32 precision tolerance
        assert!(
            (host[0] - 0.5).abs() < 0.05,
            "batch 0: expected 0.5, got {}",
            host[0]
        );
        assert!(
            (host[1] - (-1.5)).abs() < 0.05,
            "batch 1: expected -1.5, got {}",
            host[1]
        );
    }

    #[test]
    fn test_tft_quantile_rejects_bad_dims() {
        let stream = cuda_stream();
        let zeros: Vec<f32> = vec![0.0_f32; 6];
        let mut q_buf = stream.alloc_zeros::<f32>(6).unwrap();
        stream.memcpy_htod(&zeros, &mut q_buf).unwrap();

        // horizon=0 should fail
        let err = tft_quantile_to_signal(&q_buf, 2, 0, 3, &stream);
        assert!(err.is_err(), "should reject horizon=0");

        // num_quantiles=1 should fail
        let err = tft_quantile_to_signal(&q_buf, 2, 1, 1, &stream);
        assert!(err.is_err(), "should reject num_quantiles=1");
    }

    // ── backtest_fitness ────────────────────────────────────────────────

    #[test]
    fn test_backtest_fitness_normal_trades() {
        let f = backtest_fitness(1.5, 50, 30, 0.0);
        assert!((f - (-1.5)).abs() < 1e-9);
    }

    #[test]
    fn test_backtest_fitness_few_trades() {
        let f = backtest_fitness(1.5, 15, 30, 0.0);
        // -1.5 * (15/30) = -0.75
        assert!((f - (-0.75)).abs() < 1e-9);
    }

    #[test]
    fn test_backtest_fitness_zero_trades() {
        let f = backtest_fitness(1.5, 0, 30, 2.0);
        // 1 / (1 + 2) = 1/3
        assert!((f - (1.0 / 3.0)).abs() < 1e-9);
    }

    #[test]
    fn test_backtest_fitness_zero_trades_sane_thresholds() {
        let f = backtest_fitness(1.5, 0, 30, 0.0);
        // 1 / (1 + 0) = 1.0
        assert!((f - 1.0).abs() < 1e-9);
    }
}
