//! KAN (Kolmogorov-Arnold Network) Hyperparameter Optimization Adapter
//!
//! Provides `KANParams` (implementing `ParameterSpace`), `KANMetrics`,
//! and `KANTrainer` (implementing `HyperparameterOptimizable`) for
//! hyperparameter optimization of the KAN model via the unified framework.

use std::sync::Arc;
use ml_core::device::MlDevice;
use serde::{Deserialize, Serialize};
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::kan::config::KANConfig;
use crate::kan::trainable::KANTrainableAdapter;
use crate::training::unified_trainer::UnifiedTrainable;
use crate::MLError;

/// KAN model overhead in MB (weights + optimizer state)
const MODEL_OVERHEAD_MB: f64 = 30.0;
/// KAN per-sample memory in MB (spline-based, compact)
const MB_PER_SAMPLE: f64 = 0.005;

/// Hyperparameters for KAN hyperopt tuning.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct KANParams {
    /// Learning rate for AdamW optimizer (log-scale)
    pub learning_rate: f64,
    /// Number of B-spline grid points per activation
    pub grid_size: usize,
    /// B-spline order (degree + 1)
    pub spline_order: usize,
    /// Hidden layer width (used for all hidden layers)
    pub hidden_width: usize,
    /// Number of hidden layers (total layers = num_layers + 1 for output)
    pub num_layers: usize,
    /// L2 weight decay (log-scale)
    pub weight_decay: f64,
    /// Maximum gradient norm for clipping (log-scale)
    pub grad_clip: f64,
    /// Training batch size
    pub batch_size: usize,
    /// 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 KANParams {
    fn default() -> Self {
        Self {
            learning_rate: 1e-3,
            grid_size: 5,
            spline_order: 4,
            hidden_width: 32,
            num_layers: 2,
            weight_decay: 1e-4,
            grad_clip: 1.0,
            batch_size: 32,
            signal_high_bps: 10.0,
            signal_low_bps: 5.0,
        }
    }
}

/// Number of continuous parameters in the KAN parameter space.
const NUM_PARAMS: usize = 10;

impl ParameterSpace for KANParams {
    fn continuous_bounds() -> Vec<(f64, f64)> {
        vec![
            (1e-5_f64.ln(), 1e-2_f64.ln()), // learning_rate (log)
            (3.0, 12.0),                     // grid_size (linear)
            (2.0, 5.0),                      // spline_order (linear)
            (16.0, 256.0),                   // hidden_width (linear)
            (2.0, 4.0),                      // num_layers (linear)
            (1e-6_f64.ln(), 1e-2_f64.ln()),  // weight_decay (log)
            (0.5_f64.ln(), 5.0_f64.ln()),    // grad_clip (log)
            (8.0, 512.0),                    // batch_size (linear)
            (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() != NUM_PARAMS {
            return Err(MLError::ConfigError(format!("Expected {} continuous parameters, got {}", NUM_PARAMS, x.len())));
        }
        Ok(Self {
            learning_rate: x.first().copied().unwrap_or(0.0).exp(),
            grid_size: x.get(1).copied().unwrap_or(5.0).round().max(3.0) as usize,
            spline_order: x.get(2).copied().unwrap_or(4.0).round().max(2.0) as usize,
            hidden_width: x.get(3).copied().unwrap_or(32.0).round().max(16.0) as usize,
            num_layers: x.get(4).copied().unwrap_or(2.0).round().max(2.0) as usize,
            weight_decay: x.get(5).copied().unwrap_or(0.0).exp(),
            grad_clip: x.get(6).copied().unwrap_or(0.0).exp(),
            batch_size: x.get(7).copied().unwrap_or(32.0).round().max(8.0) as usize,
            signal_high_bps: x.get(8).copied().unwrap_or(10.0).clamp(1.0, 30.0),
            signal_low_bps: x.get(9).copied().unwrap_or(5.0).clamp(0.5, 15.0),
        })
    }

    fn to_continuous(&self) -> Vec<f64> {
        vec![
            self.learning_rate.ln(),
            self.grid_size as f64,
            self.spline_order as f64,
            self.hidden_width as f64,
            self.num_layers as f64,
            self.weight_decay.ln(),
            self.grad_clip.ln(),
            self.batch_size as f64,
            self.signal_high_bps,
            self.signal_low_bps,
        ]
    }

    fn param_names() -> Vec<&'static str> {
        vec![
            "learning_rate",
            "grid_size",
            "spline_order",
            "hidden_width",
            "num_layers",
            "weight_decay",
            "grad_clip",
            "batch_size",
            "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(7) {
                batch_bound.1 = max_batch;
            }
        }
        // Cap hidden_width by VRAM (index 3)
        if budget.gpu_memory_mb < 8000 {
            bounds[3] = (16.0, 64.0);
        } else if budget.gpu_memory_mb < 16000 {
            bounds[3] = (16.0, 128.0);
        } else if budget.gpu_memory_mb < 40000 {
            bounds[3] = (16.0, 192.0);
        } else {
            // ≥40GB (L40S 46GB, H100 80GB): allow full 256
        }
        bounds
    }
}

/// Metrics returned from KAN hyperopt training.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct KANMetrics {
    /// Validation loss (primary objective for optimization)
    pub val_loss: f64,
    /// Training loss at end of run
    pub train_loss: f64,
    /// Number of epochs completed
    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>,
}

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

impl KANTrainer {
    /// Create a new KAN 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 KAN hyperopt: {}", e)))?;

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

        Ok(Self {
            data_dir,
            epochs,
            device,
            training_paths: TrainingPaths::new("/tmp/ml_training", "kan", "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 KANTrainer {
    type Params = KANParams;
    type Metrics = KANMetrics;

    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 KAN: lr={:.6}, grid={}, spline_order={}, hidden_width={}, layers={}, batch={}",
            params.learning_rate, params.grid_size, params.spline_order,
            params.hidden_width, params.num_layers, 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;
        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()));
        }

        // Build layer_widths: [input, hidden, ..., hidden, output]
        let mut layer_widths = vec![feature_dim];
        for _ in 0..params.num_layers {
            layer_widths.push(params.hidden_width);
        }
        layer_widths.push(1); // Single output

        let config = KANConfig {
            grid_size: params.grid_size,
            spline_order: params.spline_order,
            layer_widths,
            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<KANMetrics, MLError> {
            let mut model = KANTrainableAdapter::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(KANMetrics {
                            val_loss: 1000.0,
                            train_loss: 1000.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
                };

                // Validation: average forward_loss over val data
                let mut val_loss_accum = 0.0_f64;
                let mut val_count = 0_usize;
                for (input, target) in val_data {
                    let vi_h = input.to_host(stream)?;
                    let vt_h = target.to_host(stream)?;
                    if let Ok(vl) = model.forward_loss(&vi_h, &vt_h) {
                        val_loss_accum += vl;
                        val_count += 1;
                    }
                }
                let val_loss = if val_count > 0 { val_loss_accum / val_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(KANMetrics {
                        val_loss: best_val_loss,
                        train_loss: last_train_loss,
                        epochs_completed: epoch + 1,
                        backtest_sharpe: None,
                        backtest_trades: None,
                    });
                }
            }

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

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

        info!(
            "KAN 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() {
        let bounds = KANParams::continuous_bounds();
        let names = KANParams::param_names();
        assert_eq!(bounds.len(), names.len());
        assert_eq!(bounds.len(), NUM_PARAMS);
    }

    #[test]
    fn test_roundtrip_continuous() {
        let params = KANParams::default();
        let continuous = params.to_continuous();
        let restored = KANParams::from_continuous(&continuous).unwrap();
        assert!(
            (params.learning_rate - restored.learning_rate).abs() < 1e-6,
            "lr mismatch: {} vs {}",
            params.learning_rate,
            restored.learning_rate
        );
        assert_eq!(params.grid_size, restored.grid_size);
        assert_eq!(params.spline_order, restored.spline_order);
        assert_eq!(params.hidden_width, restored.hidden_width);
        assert_eq!(params.num_layers, restored.num_layers);
        assert!(
            (params.weight_decay - restored.weight_decay).abs() / params.weight_decay < 1e-6,
            "weight_decay mismatch"
        );
        assert!(
            (params.grad_clip - restored.grad_clip).abs() < 1e-6,
            "grad_clip mismatch"
        );
        assert_eq!(params.batch_size, restored.batch_size);
    }

    #[test]
    fn test_from_continuous_wrong_length_errors() {
        let result = KANParams::from_continuous(&[0.1, 0.2]);
        assert!(result.is_err());
        let err_msg = format!("{}", result.unwrap_err());
        assert!(
            err_msg.contains("Expected 10"),
            "Error should mention expected count: {}",
            err_msg
        );
    }

    #[test]
    fn test_bounds_are_valid() {
        for (i, (min, max)) in KANParams::continuous_bounds().iter().enumerate() {
            assert!(
                min < max,
                "Invalid bounds for param {} ({}): {} >= {}",
                i,
                KANParams::param_names().get(i).copied().unwrap_or("?"),
                min,
                max
            );
        }
    }

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

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

    #[test]
    fn test_continuous_length() {
        let params = KANParams::default();
        let continuous = params.to_continuous();
        assert_eq!(continuous.len(), NUM_PARAMS);
    }
}
