//! V10 Block DD — Intraday seasonality residuals + macro-event stage encoding.
//!
//! ## Motivation
//!
//! Intraday market activity is dominated by **seasonal patterns**: the U-shape
//! of volatility (high at open/close, low midday), the morning trade-count
//! peak, lunch-hour quiescence. A model that doesn't deseasonalize sees these
//! patterns as "noise" — features at 10:00 ET differ from features at 14:00 ET
//! systematically, even when nothing market-meaningful is happening.
//!
//! Per Aleti, Bollerslev & Siggaard (2025, *Management Science*) "Intraday
//! Market Return Predictability Culled from the Factor Zoo": deseasonalized
//! intraday vol residual is a load-bearing feature in their factor stack.
//! Per Boudt et al. (2024, MS 2024.06215) "Universal HF Periodicities": the
//! strongest periodicity is in **trade count**, not volume.
//!
//! ## What's emitted
//!
//! 1. `vol_residual`        — `realized_vol_t − seasonal_mean_vol(time_of_day_t)`
//! 2. `trade_count_residual`— `trade_count_t − seasonal_mean_count(time_of_day_t)`
//! 3. `event_pre`           — 1 if in [−30min, 0min) before FOMC/NFP event
//! 4. `event_at`            — 1 if within ±1min of announcement
//! 5. `event_immediate_post`— 1 if in (0, +30min] post-announcement
//! 6. `event_far_post`      — 1 if in (+30min, +2hr] post-announcement
//!
//! Total: **6 features**.
//!
//! ## Event calendar (ES.FUT 2024-Q1)
//!
//! - FOMC announcements: Jan 31 19:00 UTC, Mar 20 18:00 UTC
//! - NFP releases (first-Friday 13:30 UTC): Jan 5, Feb 2, Mar 8 (all 13:30 UTC)
//!
//! These are hardcoded for v10. Production deployment would consume a
//! calendar config.

/// Number of intraday buckets for seasonality (96 = 15-minute resolution).
pub const SEASONALITY_BUCKETS: usize = 96;

/// EMA decay for the per-bucket running mean (slow tracker).
pub const SEASONALITY_ALPHA: f64 = 0.02;

/// Hardcoded FOMC/NFP announcement timestamps (nanoseconds since Unix epoch)
/// for ES.FUT 2024-Q1.
const Q1_2024_EVENT_TS_NS: &[i64] = &[
    // FOMC: Jan 31, 2024 19:00 UTC
    1_706_727_600 * 1_000_000_000,
    // NFP: Feb 2, 2024 13:30 UTC
    1_706_880_600 * 1_000_000_000,
    // NFP: Mar 8, 2024 13:30 UTC
    1_709_904_600 * 1_000_000_000,
    // FOMC: Mar 20, 2024 18:00 UTC (DST)
    1_710_957_600 * 1_000_000_000,
    // NFP: Jan 5, 2024 13:30 UTC
    1_704_461_400 * 1_000_000_000,
];

/// Per-bucket online mean estimator. EMA-smoothed for non-stationarity.
#[derive(Debug, Clone)]
pub struct SeasonalityResidual {
    n_buckets: usize,
    means: Vec<f64>,
    counts: Vec<u64>,
    alpha: f64,
}

impl SeasonalityResidual {
    pub fn new(n_buckets: usize, alpha: f64) -> Self {
        Self {
            n_buckets,
            means: vec![0.0; n_buckets],
            counts: vec![0; n_buckets],
            alpha,
        }
    }

    /// Bucket index for a timestamp in nanoseconds since Unix epoch.
    /// Uses UTC seconds-since-midnight modulo 24h, partitioned into
    /// `n_buckets` equal sub-windows.
    pub fn bucket_for_timestamp(&self, timestamp_ns: i64) -> usize {
        let secs_since_midnight = (timestamp_ns / 1_000_000_000).rem_euclid(86400);
        let bucket_size_secs = 86400_i64 / self.n_buckets as i64;
        let b = (secs_since_midnight / bucket_size_secs) as usize;
        b.min(self.n_buckets - 1)
    }

    /// Update with a new observation; return `value − bucket_mean` (the
    /// **residual** above seasonal baseline). On first observation in a
    /// bucket, returns 0 (no baseline yet).
    pub fn update_and_residual(&mut self, value: f64, timestamp_ns: i64) -> f64 {
        let b = self.bucket_for_timestamp(timestamp_ns);
        let residual = if self.counts[b] == 0 {
            self.means[b] = value;
            0.0
        } else {
            let r = value - self.means[b];
            self.means[b] = self.alpha * value + (1.0 - self.alpha) * self.means[b];
            r
        };
        self.counts[b] = self.counts[b].saturating_add(1);
        residual
    }

    pub fn reset(&mut self) {
        for m in &mut self.means {
            *m = 0.0;
        }
        for c in &mut self.counts {
            *c = 0;
        }
    }
}

/// Compute the 4-stage event encoding `[pre, at, immediate_post, far_post]`
/// relative to the closest hardcoded FOMC/NFP event timestamp.
///
/// Stage windows (in seconds before/after announcement):
/// - `pre`:             [−1800, 0)
/// - `at`:              [−60, +60]
/// - `immediate_post`:  (60, +1800]
/// - `far_post`:        (+1800, +7200]
///
/// If none of the stages apply (more than 2hrs out from any event), all zero.
pub fn event_stage_encoding(timestamp_ns: i64) -> [f64; 4] {
    let mut stage = [0.0_f64; 4];
    for &event_ts in Q1_2024_EVENT_TS_NS {
        let delta_secs = (timestamp_ns - event_ts) / 1_000_000_000;
        if delta_secs >= -1800 && delta_secs < -60 {
            stage[0] = 1.0;
        } else if (-60..=60).contains(&delta_secs) {
            stage[1] = 1.0;
        } else if delta_secs > 60 && delta_secs <= 1800 {
            stage[2] = 1.0;
        } else if delta_secs > 1800 && delta_secs <= 7200 {
            stage[3] = 1.0;
        }
    }
    stage
}

/// V10 Block DD — combined seasonality + event aggregator.
///
/// Holds two `SeasonalityResidual` instances (one for vol, one for trade
/// count) plus emits the 4 event-stage flags per bar.
#[derive(Debug, Clone)]
pub struct SeasonalityAndEventFeatures {
    pub vol_residual: SeasonalityResidual,
    pub trade_count_residual: SeasonalityResidual,
}

impl SeasonalityAndEventFeatures {
    pub fn new() -> Self {
        Self {
            vol_residual: SeasonalityResidual::new(SEASONALITY_BUCKETS, SEASONALITY_ALPHA),
            trade_count_residual: SeasonalityResidual::new(SEASONALITY_BUCKETS, SEASONALITY_ALPHA),
        }
    }

    /// Compute the 6 Block DD features.
    /// `vol` = realized vol or any vol proxy for the current bar.
    /// `trade_count` = number of trades in the current bar.
    pub fn update(&mut self, vol: f64, trade_count: f64, timestamp_ns: i64) -> [f64; 6] {
        let vol_resid = self.vol_residual.update_and_residual(vol, timestamp_ns);
        let tc_resid = self
            .trade_count_residual
            .update_and_residual(trade_count, timestamp_ns);
        let stages = event_stage_encoding(timestamp_ns);
        [vol_resid, tc_resid, stages[0], stages[1], stages[2], stages[3]]
    }

    pub fn reset(&mut self) {
        self.vol_residual.reset();
        self.trade_count_residual.reset();
    }
}

impl Default for SeasonalityAndEventFeatures {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_seasonality_residual_zero_first_observation() {
        let mut sr = SeasonalityResidual::new(96, 0.02);
        let ts = 1_700_000_000_000_000_000_i64;
        let r = sr.update_and_residual(0.1, ts);
        assert_eq!(r, 0.0, "first observation in a bucket → residual = 0");
    }

    #[test]
    fn test_seasonality_residual_converges_with_repeated_values() {
        let mut sr = SeasonalityResidual::new(96, 0.5); // fast EMA for test
        let ts = 1_700_000_000_000_000_000_i64;
        // First call sets baseline to 1.0, subsequent calls converge
        sr.update_and_residual(1.0, ts);
        for _ in 0..20 {
            sr.update_and_residual(1.0, ts);
        }
        let r = sr.update_and_residual(1.0, ts);
        assert!(r.abs() < 1e-6, "convergent input → residual → 0, got {r}");
    }

    #[test]
    fn test_seasonality_residual_detects_anomaly_after_warmup() {
        let mut sr = SeasonalityResidual::new(96, 0.5);
        let ts = 1_700_000_000_000_000_000_i64;
        // Warm up bucket with vol = 0.5
        for _ in 0..20 {
            sr.update_and_residual(0.5, ts);
        }
        // Anomalous vol spike of 5.0
        let r = sr.update_and_residual(5.0, ts);
        assert!(r > 4.0, "5x anomaly should produce residual ≈ 4.5, got {r}");
    }

    #[test]
    fn test_different_times_use_different_buckets() {
        let mut sr = SeasonalityResidual::new(96, 0.5);
        let ts_a = 1_700_000_000_000_000_000_i64; // some time
        let ts_b = ts_a + 8 * 3600 * 1_000_000_000; // 8 hours later → different bucket
        sr.update_and_residual(1.0, ts_a);
        // Same value at different time-of-day → first obs of that bucket → 0
        let r = sr.update_and_residual(1.0, ts_b);
        assert_eq!(r, 0.0, "different bucket → first-obs residual = 0");
    }

    #[test]
    fn test_event_stage_at_fomc_announcement() {
        // Jan 31, 2024 19:00 UTC exactly
        let ts = 1_706_727_600 * 1_000_000_000_i64;
        let stages = event_stage_encoding(ts);
        assert_eq!(stages, [0.0, 1.0, 0.0, 0.0], "exact announcement → 'at' stage");
    }

    #[test]
    fn test_event_stage_pre_window() {
        // 20 minutes before Jan 31 FOMC
        let ts = (1_706_727_600 - 1200) * 1_000_000_000_i64;
        let stages = event_stage_encoding(ts);
        assert_eq!(stages, [1.0, 0.0, 0.0, 0.0], "20min pre → 'pre' stage");
    }

    #[test]
    fn test_event_stage_immediate_post() {
        // 10 minutes after Mar 20 FOMC
        let ts = (1_710_957_600 + 600) * 1_000_000_000_i64;
        let stages = event_stage_encoding(ts);
        assert_eq!(stages, [0.0, 0.0, 1.0, 0.0], "10min post → 'immediate_post'");
    }

    #[test]
    fn test_event_stage_far_post() {
        // 90 minutes after NFP Feb 2
        let ts = (1_706_880_600 + 5400) * 1_000_000_000_i64;
        let stages = event_stage_encoding(ts);
        assert_eq!(stages, [0.0, 0.0, 0.0, 1.0], "90min post → 'far_post'");
    }

    #[test]
    fn test_event_stage_no_event_all_zero() {
        // A timestamp far from any event (random Tuesday afternoon)
        let ts = 1_708_000_000_000_000_000_i64;
        let stages = event_stage_encoding(ts);
        assert_eq!(stages, [0.0, 0.0, 0.0, 0.0], "no nearby event → all zeros");
    }

    #[test]
    fn test_seasonality_and_event_features_combined_output_shape() {
        let mut sae = SeasonalityAndEventFeatures::new();
        let ts = 1_708_000_000_000_000_000_i64;
        let features = sae.update(0.1, 50.0, ts);
        // 6 features: [vol_resid, tc_resid, pre, at, post_imm, post_far]
        assert_eq!(features.len(), 6);
        // First call: residuals are 0; event flags also 0 (no nearby event)
        assert_eq!(features, [0.0; 6]);
    }
}
