//! Hyperopt adapter for xLSTM (Extended LSTM).
//!
//! Provides `XLSTMParams` (implementing `ParameterSpace`), `XLSTMMetrics`,
//! and `XLSTMTrainer` (implementing `HyperparameterOptimizable`) for
//! hyperparameter optimization of the xLSTM model via the unified framework.

use std::sync::Arc;
use ml_core::device::MlDevice;
use std::path::PathBuf;
use tracing::{info, warn};

use crate::features::extract_ml_features;
use crate::features::extraction::OHLCVBar;
use crate::hyperopt::paths::TrainingPaths;
use crate::hyperopt::traits::{HardwareBudget, HyperparameterOptimizable, ParameterSpace};
use crate::training::unified_trainer::UnifiedTrainable;
use crate::xlstm::config::XLSTMConfig;
use crate::xlstm::trainable::XLSTMTrainableAdapter;
use crate::MLError;

/// xLSTM model overhead in MB (weights + optimizer state)
const MODEL_OVERHEAD_MB: f64 = 60.0;
/// xLSTM per-sample memory in MB (extended LSTM states)
const MB_PER_SAMPLE: f64 = 0.008;

/// Hyperparameters for xLSTM hyperopt tuning.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct XLSTMParams {
    pub learning_rate: f64,
    pub hidden_dim: usize,
    pub num_blocks: usize,
    pub num_heads: usize,
    pub slstm_ratio: f64,
    pub dropout: f64,
    pub batch_size: usize,
    pub weight_decay: f64,
    pub grad_clip: f64,
    /// Signal high threshold in basis points (GPU backtest action mapping)
    pub signal_high_bps: f64,
    /// Signal low threshold in basis points (GPU backtest action mapping)
    pub signal_low_bps: f64,
}

impl Default for XLSTMParams {
    fn default() -> Self {
        Self {
            learning_rate: 1e-3,
            hidden_dim: 64,
            num_blocks: 4,
            num_heads: 4,
            slstm_ratio: 0.5,
            dropout: 0.1,
            batch_size: 32,
            weight_decay: 1e-4,
            grad_clip: 1.0,
            signal_high_bps: 10.0,
            signal_low_bps: 5.0,
        }
    }
}

impl ParameterSpace for XLSTMParams {
    fn continuous_bounds() -> Vec<(f64, f64)> {
        vec![
            (1e-5_f64.ln(), 1e-2_f64.ln()),  // learning_rate (log)
            (32.0, 2048.0),                    // hidden_dim
            (2.0, 8.0),                        // num_blocks
            (1.0, 8.0),                        // num_heads
            (0.0, 1.0),                        // slstm_ratio
            (0.0, 0.5),                        // dropout
            (8.0, 512.0),                      // batch_size
            (1e-6_f64.ln(), 1e-2_f64.ln()),   // weight_decay (log)
            (0.5_f64.ln(), 5.0_f64.ln()),     // grad_clip (log)
            (1.0, 30.0),                      // signal_high_bps
            (0.5, 15.0),                      // signal_low_bps
        ]
    }

    fn from_continuous(x: &[f64]) -> Result<Self, MLError> {
        if x.len() != 11 {
            return Err(MLError::ConfigError(format!("Expected 11 params, got {}", x.len())));
        }
        let hidden_dim = x.get(1).copied().unwrap_or(64.0).round().max(32.0) as usize;
        let num_heads = x.get(3).copied().unwrap_or(4.0).round().max(1.0) as usize;
        // Ensure hidden_dim is divisible by num_heads
        let hidden_dim = (hidden_dim / num_heads) * num_heads;
        Ok(Self {
            learning_rate: x.first().copied().unwrap_or(-6.9).exp(),
            hidden_dim: hidden_dim.max(num_heads), // at least 1 per head
            num_blocks: x.get(2).copied().unwrap_or(4.0).round().max(2.0) as usize,
            num_heads,
            slstm_ratio: x.get(4).copied().unwrap_or(0.5).clamp(0.0, 1.0),
            dropout: x.get(5).copied().unwrap_or(0.1).clamp(0.0, 0.5),
            batch_size: x.get(6).copied().unwrap_or(32.0).round().max(8.0) as usize,
            weight_decay: x.get(7).copied().unwrap_or(-9.21).exp(),
            grad_clip: x.get(8).copied().unwrap_or(0.0).exp(),
            signal_high_bps: x.get(9).copied().unwrap_or(10.0).clamp(1.0, 30.0),
            signal_low_bps: x.get(10).copied().unwrap_or(5.0).clamp(0.5, 15.0),
        })
    }

    fn to_continuous(&self) -> Vec<f64> {
        vec![
            self.learning_rate.ln(),
            self.hidden_dim as f64,
            self.num_blocks as f64,
            self.num_heads as f64,
            self.slstm_ratio,
            self.dropout,
            self.batch_size as f64,
            self.weight_decay.ln(),
            self.grad_clip.ln(),
            self.signal_high_bps,
            self.signal_low_bps,
        ]
    }

    fn param_names() -> Vec<&'static str> {
        vec![
            "learning_rate", "hidden_dim", "num_blocks", "num_heads",
            "slstm_ratio", "dropout", "batch_size", "weight_decay", "grad_clip",
            "signal_high_bps", "signal_low_bps",
        ]
    }

    fn continuous_bounds_for(budget: &HardwareBudget) -> Vec<(f64, f64)> {
        let mut bounds = Self::continuous_bounds();
        if let Some(max_batch) = budget.max_batch_size(MODEL_OVERHEAD_MB, MB_PER_SAMPLE, 8.0, 4096.0) {
            if let Some(batch_bound) = bounds.get_mut(6) {
                batch_bound.1 = max_batch;
            }
        }
        // Cap hidden_dim by VRAM (index 1)
        if budget.gpu_memory_mb < 8000 {
            bounds[1] = (32.0, 256.0);
        } else if budget.gpu_memory_mb < 16000 {
            bounds[1] = (32.0, 512.0);
        } else if budget.gpu_memory_mb < 40000 {
            bounds[1] = (32.0, 1024.0);
        } else {
            // ≥40GB (L40S 46GB, H100 80GB): allow full 2048
        }
        bounds
    }
}

/// Metrics returned from xLSTM hyperopt training.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct XLSTMMetrics {
    pub val_loss: f64,
    pub train_loss: f64,
    pub directional_accuracy: f64,
    pub epochs_completed: usize,
    /// GPU walk-forward backtest Sharpe ratio
    pub backtest_sharpe: Option<f32>,
    /// GPU walk-forward backtest total trades
    pub backtest_trades: Option<u32>,
}

/// xLSTM trainer for hyperparameter optimization.
///
/// Wraps the `XLSTMTrainableAdapter` (which implements `UnifiedTrainable`)
/// and drives it through the `HyperparameterOptimizable` interface.
#[derive(Debug)]
pub struct XLSTMTrainer {
    data_dir: PathBuf,
    epochs: usize,
    device: MlDevice,
    training_paths: TrainingPaths,
    early_stopping_patience: usize,
    trial_counter: usize,
    preloaded_bars: Option<Arc<[OHLCVBar]>>,
}

impl XLSTMTrainer {
    /// Create a new xLSTM trainer.
    ///
    /// # Arguments
    /// * `data_dir` - Directory containing .dbn/.dbn.zst files
    /// * `epochs` - Number of training epochs per trial
    pub fn new<P: Into<PathBuf>>(data_dir: P, epochs: usize) -> Result<Self, MLError> {
        let data_dir = data_dir.into();
        if !data_dir.exists() {
            return Err(MLError::ConfigError(format!("Data directory not found: {}", data_dir.display())));
        }

        let device = MlDevice::cuda(0)
            .map_err(|e| MLError::ConfigError(format!("CUDA GPU required for xLSTM hyperopt: {}", e)))?;

        info!(
            "xLSTM Trainer initialized: Device={:?}, Data={}, Epochs={}",
            device, data_dir.display(), epochs
        );

        Ok(Self {
            data_dir,
            epochs,
            device,
            training_paths: TrainingPaths::new("/tmp/ml_training", "xlstm", "default"),
            early_stopping_patience: 10,
            trial_counter: 0,
            preloaded_bars: None,
        })
    }

    /// Set training paths configuration.
    pub fn with_training_paths(mut self, paths: TrainingPaths) -> Self {
        self.training_paths = paths;
        self
    }

    /// Configure early stopping patience.
    pub fn with_early_stopping(mut self, patience: usize) -> Self {
        self.early_stopping_patience = patience;
        self
    }

    /// Preload DBN data once for reuse across all hyperopt trials.
    pub fn preload_data(&mut self) -> Result<(), MLError> {
        if self.preloaded_bars.is_some() {
            return Ok(());
        }
        let bars = super::dbn_loader::load_bars_from_dbn_dir(&self.data_dir)
            .map_err(|e| MLError::ModelError(format!("Failed to preload DBN data: {}", e)))?;
        info!("Preloaded {} OHLCV bars for reuse across trials", bars.len());
        self.preloaded_bars = Some(Arc::from(bars));
        Ok(())
    }

    /// Check if data has been preloaded.
    pub fn has_preloaded_data(&self) -> bool {
        self.preloaded_bars.is_some()
    }
}

impl HyperparameterOptimizable for XLSTMTrainer {
    type Params = XLSTMParams;
    type Metrics = XLSTMMetrics;

    fn train_with_params(&mut self, params: Self::Params) -> Result<Self::Metrics, MLError> {
        let trial_start = std::time::Instant::now();
        let current_trial = self.trial_counter;
        self.trial_counter += 1;

        info!(
            "Training xLSTM: lr={:.6}, hidden={}, blocks={}, heads={}, slstm_ratio={:.2}, batch={}",
            params.learning_rate, params.hidden_dim, params.num_blocks,
            params.num_heads, params.slstm_ratio, params.batch_size
        );

        self.training_paths.create_all().map_err(|e| {
            MLError::ModelError(format!("Failed to create training directories: {}", e))
        })?;

        let bars = if let Some(ref preloaded) = self.preloaded_bars {
            preloaded.to_vec() // cpu-side Arc<[OHLCVBar]> clone
        } else {
            super::dbn_loader::load_bars_from_dbn_dir(&self.data_dir)
                .map_err(|e| MLError::ModelError(format!("Failed to load DBN data: {}", e)))?
        };

        let features = extract_ml_features(&bars)
            .map_err(|e| MLError::ModelError(format!("Failed to extract features: {}", e)))?;

        if features.len() < 2 {
            return Err(MLError::ModelError("Insufficient features extracted".to_owned()));
        }

        let feature_dim = 51;

        // xLSTM uses flat input (the adapter handles internal state)
        let pairs = crate::hyperopt::shared_data::build_flat_pairs(
            &features, &bars, feature_dim, &self.device,
        )?;

        let split = (pairs.len() as f64 * 0.8) as usize;
        let train_data = &pairs[..split];
        let val_data = &pairs[split..];

        if val_data.len() < 2 {
            return Err(MLError::ModelError("Validation set too small".to_owned()));
        }

        let config = XLSTMConfig {
            input_dim: feature_dim,
            hidden_dim: params.hidden_dim,
            num_blocks: params.num_blocks,
            num_heads: params.num_heads,
            slstm_ratio: params.slstm_ratio,
            output_dim: 1,
            dropout: params.dropout,
            learning_rate: params.learning_rate,
            weight_decay: params.weight_decay,
            grad_clip: params.grad_clip,
        };

        let training_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result<XLSTMMetrics, MLError> {
            let mut model = XLSTMTrainableAdapter::new(config)?;

            let mut best_val_loss = f64::MAX;
            let mut patience_counter = 0_usize;
            let mut last_train_loss = 0.0_f64;

            for epoch in 0..self.epochs {
                let mut loss_accum = 0.0_f64;
                let mut batch_count = 0_usize;

                let stream = self.device.cuda_stream()
                    .map_err(|e| MLError::DeviceError(format!("CUDA stream: {e}")))?;
                for (input, target) in train_data {
                    let input_host = input.to_host(stream)?;
                    let target_host = target.to_host(stream)?;
                    let loss_val = model.forward_loss(&input_host, &target_host)?;

                    if batch_count == 0 && (loss_val.is_nan() || loss_val.is_infinite()) {
                        return Ok(XLSTMMetrics {
                            val_loss: 1000.0,
                            train_loss: 1000.0,
                            directional_accuracy: 0.0,
                            epochs_completed: epoch,
                            backtest_sharpe: None,
                            backtest_trades: None,
                        });
                    }

                    model.backward(loss_val)?;
                    model.optimizer_step()?;
                    loss_accum += loss_val;
                    batch_count += 1;
                }

                last_train_loss = if batch_count > 0 {
                    loss_accum / batch_count as f64
                } else {
                    0.0
                };

                let mut vl_accum = 0.0_f64;
                let mut vl_count = 0_usize;
                for (vi, vt) in val_data {
                    let vi_h = vi.to_host(stream)?;
                    let vt_h = vt.to_host(stream)?;
                    if let Ok(vl) = model.forward_loss(&vi_h, &vt_h) {
                        vl_accum += vl;
                        vl_count += 1;
                    }
                }
                let val_loss = if vl_count > 0 { vl_accum / vl_count as f64 } else { 1000.0 };

                if val_loss < best_val_loss {
                    best_val_loss = val_loss;
                    patience_counter = 0;
                } else {
                    patience_counter += 1;
                }

                if epoch % 10 == 0 {
                    info!(
                        "  Epoch {}/{}: train_loss={:.6}, val_loss={:.6}",
                        epoch + 1, self.epochs, last_train_loss, val_loss
                    );
                }

                if patience_counter >= self.early_stopping_patience {
                    info!("Early stopping at epoch {}", epoch + 1);
                    return Ok(XLSTMMetrics {
                        val_loss: best_val_loss,
                        train_loss: last_train_loss,
                        directional_accuracy: 0.0,
                        epochs_completed: epoch + 1,
                        backtest_sharpe: None,
                        backtest_trades: None,
                    });
                }
            }

            Ok(XLSTMMetrics {
                val_loss: best_val_loss,
                train_loss: last_train_loss,
                directional_accuracy: 0.0,
                epochs_completed: self.epochs,
                backtest_sharpe: None,
                backtest_trades: None,
            })
        }));

        let metrics = match training_result {
            Ok(Ok(m)) => m,
            Ok(Err(e)) => {
                warn!("xLSTM training failed: {}", e);
                XLSTMMetrics { val_loss: 1000.0, train_loss: 1000.0, directional_accuracy: 0.0, epochs_completed: 0, backtest_sharpe: None, backtest_trades: None }
            }
            Err(_) => {
                warn!("xLSTM training panicked (likely OOM)");
                XLSTMMetrics { val_loss: 1000.0, train_loss: 1000.0, directional_accuracy: 0.0, epochs_completed: 0, backtest_sharpe: None, backtest_trades: None }
            }
        };

        info!(
            "xLSTM training completed: val_loss={:.6}, train_loss={:.6}, epochs={}",
            metrics.val_loss, metrics.train_loss, metrics.epochs_completed
        );

        let duration_secs = trial_start.elapsed().as_secs_f64();
        let trial_result = crate::hyperopt::traits::TrialResult {
            trial_num: current_trial,
            params,
            objective: Self::extract_objective(&metrics),
            duration_secs,
            metrics: None,
        };
        std::fs::create_dir_all(self.training_paths.hyperopt_dir()).ok();
        crate::hyperopt::shared_data::write_trial_result_json(
            &self.training_paths.hyperopt_dir(),
            &trial_result,
        ).ok();

        if self.device.is_cuda() {
            std::thread::sleep(std::time::Duration::from_millis(100));
        }

        Ok(metrics)
    }

    fn extract_objective(metrics: &Self::Metrics) -> f64 {
        if let (Some(sharpe), Some(trades)) = (metrics.backtest_sharpe, metrics.backtest_trades) {
            return crate::cuda_pipeline::signal_adapter::backtest_fitness(sharpe, trades, 30, 0.0);
        }
        metrics.val_loss
    }
}

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

    #[test]
    fn test_bounds_count_matches_param_names() {
        assert_eq!(
            XLSTMParams::continuous_bounds().len(),
            XLSTMParams::param_names().len()
        );
    }

    #[test]
    fn test_roundtrip_continuous() {
        let params = XLSTMParams::default();
        let continuous = params.to_continuous();
        let restored = XLSTMParams::from_continuous(&continuous).unwrap();
        assert!((params.learning_rate - restored.learning_rate).abs() < 1e-6);
        assert_eq!(params.num_blocks, restored.num_blocks);
        assert_eq!(params.num_heads, restored.num_heads);
    }

    #[test]
    fn test_from_continuous_wrong_length_errors() {
        let result = XLSTMParams::from_continuous(&[0.1, 0.2]);
        assert!(result.is_err());
    }

    #[test]
    fn test_bounds_are_valid() {
        for (min, max) in XLSTMParams::continuous_bounds() {
            assert!(min < max, "Invalid bounds: {min} >= {max}");
        }
    }

    #[test]
    fn test_default_within_bounds() {
        let params = XLSTMParams::default();
        let continuous = params.to_continuous();
        let bounds = XLSTMParams::continuous_bounds();
        for (i, (val, (min, max))) in continuous.iter().zip(bounds.iter()).enumerate() {
            assert!(
                *val >= *min && *val <= *max,
                "Param {} ({}) = {} outside [{}, {}]",
                i,
                XLSTMParams::param_names().get(i).unwrap_or(&"?"),
                val, min, max
            );
        }
    }

    #[test]
    fn test_hidden_dim_divisible_by_heads() {
        // hidden=65, heads=4 → should round to 64
        let x = XLSTMParams {
            hidden_dim: 65,
            num_heads: 4,
            ..XLSTMParams::default()
        };
        let c = x.to_continuous();
        let restored = XLSTMParams::from_continuous(&c).unwrap();
        assert_eq!(restored.hidden_dim % restored.num_heads, 0);
    }

    #[test]
    fn test_metrics_default() {
        let metrics = XLSTMMetrics::default();
        assert_eq!(metrics.val_loss, 0.0);
    }
}
