#![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,
)]
//! Run Bars Test Suite
//!
//! Tests for run bar sampling - bars formed when consecutive buy/sell ticks exceed threshold.
//! Tests cover:
//! - Consecutive buy run counting
//! - Consecutive sell run counting
//! - Bar formation at run threshold
//! - Direction change resets counter
//! - Performance requirements (<50μs per tick)

use chrono::{TimeZone, Utc};
use ml::features::alternative_bars::RunBarSampler;
use std::time::Instant;

fn ts(secs: i64) -> chrono::DateTime<chrono::Utc> {
    Utc.timestamp_opt(secs, 0).unwrap()
}

#[test]
fn test_run_bar_consecutive_buys() {
    let mut sampler = RunBarSampler::new(5); // Threshold of 5 consecutive buys

    // Send 4 buy ticks (price increasing) - should not emit bar
    assert!(sampler.update(100.0, 10.0, ts(1000)).is_none());
    assert!(sampler.update(100.1, 10.0, ts(1001)).is_none());
    assert!(sampler.update(100.2, 10.0, ts(1002)).is_none());
    assert!(sampler.update(100.3, 10.0, ts(1003)).is_none());

    // 5th buy tick should emit bar
    let bar = sampler.update(100.4, 10.0, ts(1004));
    assert!(bar.is_some());

    let bar = bar.unwrap();
    assert_eq!(bar.open, 100.0);
    assert_eq!(bar.high, 100.4);
    assert_eq!(bar.low, 100.0);
    assert_eq!(bar.close, 100.4);
    assert_eq!(bar.volume, 50.0); // 5 ticks * 10 volume
    assert_eq!(bar.timestamp, ts(1000));
}

#[test]
fn test_run_bar_consecutive_sells() {
    let mut sampler = RunBarSampler::new(5); // Threshold of 5 consecutive sells

    // Send 4 sell ticks (price decreasing) - should not emit bar
    assert!(sampler.update(100.0, 10.0, ts(1000)).is_none());
    assert!(sampler.update(99.9, 10.0, ts(1001)).is_none());
    assert!(sampler.update(99.8, 10.0, ts(1002)).is_none());
    assert!(sampler.update(99.7, 10.0, ts(1003)).is_none());

    // 5th sell tick should emit bar
    let bar = sampler.update(99.6, 10.0, ts(1004));
    assert!(bar.is_some());

    let bar = bar.unwrap();
    assert_eq!(bar.open, 100.0);
    assert_eq!(bar.high, 100.0);
    assert_eq!(bar.low, 99.6);
    assert_eq!(bar.close, 99.6);
    assert_eq!(bar.volume, 50.0);
    assert_eq!(bar.timestamp, ts(1000));
}

#[test]
fn test_run_bar_direction_change_resets_counter() {
    let mut sampler = RunBarSampler::new(5);

    // Send 3 buy ticks
    assert!(sampler.update(100.0, 10.0, ts(1000)).is_none());
    assert!(sampler.update(100.1, 10.0, ts(1001)).is_none());
    assert!(sampler.update(100.2, 10.0, ts(1002)).is_none());

    // Direction change - sell tick (should reset counter)
    assert!(sampler.update(100.1, 10.0, ts(1003)).is_none());

    // Send 3 more sell ticks (total 4 sells, but counter reset so no bar yet)
    assert!(sampler.update(100.0, 10.0, ts(1004)).is_none());
    assert!(sampler.update(99.9, 10.0, ts(1005)).is_none());
    assert!(sampler.update(99.8, 10.0, ts(1006)).is_none());

    // 5th sell tick should emit bar
    let bar = sampler.update(99.7, 10.0, ts(1007));
    assert!(bar.is_some());

    let bar = bar.unwrap();
    assert_eq!(bar.open, 100.1); // Start from direction change
    assert_eq!(bar.close, 99.7);
    assert_eq!(bar.volume, 50.0); // 5 ticks * 10 volume
}

#[test]
fn test_run_bar_equal_price_no_direction() {
    let mut sampler = RunBarSampler::new(5);

    // Send ticks with same price (no clear direction)
    assert!(sampler.update(100.0, 10.0, ts(1000)).is_none());
    assert!(sampler.update(100.0, 10.0, ts(1001)).is_none());
    assert!(sampler.update(100.0, 10.0, ts(1002)).is_none());
    assert!(sampler.update(100.0, 10.0, ts(1003)).is_none());
    assert!(sampler.update(100.0, 10.0, ts(1004)).is_none());

    // Should not emit bar even after 5 ticks (no directional run)
    assert!(sampler.update(100.0, 10.0, ts(1005)).is_none());
}

#[test]
fn test_run_bar_multiple_bars() {
    let mut sampler = RunBarSampler::new(3); // Lower threshold for faster testing

    // First bar: 3 buys
    assert!(sampler.update(100.0, 10.0, ts(1000)).is_none());
    assert!(sampler.update(100.1, 10.0, ts(1001)).is_none());
    let bar1 = sampler.update(100.2, 10.0, ts(1002));
    assert!(bar1.is_some());
    assert_eq!(bar1.unwrap().close, 100.2);

    // Second bar: 3 sells
    assert!(sampler.update(100.1, 10.0, ts(1003)).is_none());
    assert!(sampler.update(100.0, 10.0, ts(1004)).is_none());
    let bar2 = sampler.update(99.9, 10.0, ts(1005));
    assert!(bar2.is_some());
    assert_eq!(bar2.unwrap().close, 99.9);

    // Third bar: 3 buys
    assert!(sampler.update(100.0, 10.0, ts(1006)).is_none());
    assert!(sampler.update(100.1, 10.0, ts(1007)).is_none());
    let bar3 = sampler.update(100.2, 10.0, ts(1008));
    assert!(bar3.is_some());
    assert_eq!(bar3.unwrap().close, 100.2);
}

#[test]
fn test_run_bar_threshold_boundaries() {
    // Test threshold of 1 (every tick is a bar)
    let mut sampler = RunBarSampler::new(1);
    let bar = sampler.update(100.0, 10.0, ts(1000));
    assert!(bar.is_none()); // First tick doesn't have direction yet

    let bar = sampler.update(100.1, 10.0, ts(1001));
    assert!(bar.is_some()); // Second tick has direction

    // Test larger threshold
    let mut sampler = RunBarSampler::new(100);
    for i in 0..99 {
        assert!(sampler
            .update(100.0 + (i as f64 * 0.01), 10.0, ts(1000 + i))
            .is_none());
    }
    let bar = sampler.update(100.99, 10.0, ts(1099));
    assert!(bar.is_some());
    assert_eq!(bar.unwrap().volume, 1000.0); // 100 ticks * 10 volume
}

#[test]
fn test_run_bar_ohlcv_accuracy() {
    let mut sampler = RunBarSampler::new(5);

    // Send 5 consecutive buy ticks (each price > previous) with varying prices
    // to test OHLCV tracking during a run
    sampler.update(100.0, 5.0, ts(1000)); // Tick 1: Open (no direction yet)
    sampler.update(100.2, 10.0, ts(1001)); // Tick 2: Buy (100.2 > 100.0)
    sampler.update(100.5, 15.0, ts(1002)); // Tick 3: Buy (100.5 > 100.2)
    sampler.update(100.8, 20.0, ts(1003)); // Tick 4: Buy (100.8 > 100.5)
    let bar = sampler.update(101.0, 25.0, ts(1004)); // Tick 5: Buy (101.0 > 100.8) -> EMIT

    assert!(bar.is_some());
    let bar = bar.unwrap();
    assert_eq!(bar.open, 100.0);
    assert_eq!(bar.high, 101.0);
    assert_eq!(bar.low, 100.0);
    assert_eq!(bar.close, 101.0);
    assert_eq!(bar.volume, 75.0); // 5 + 10 + 15 + 20 + 25
    assert_eq!(bar.timestamp, ts(1000));
}

#[test]
fn test_run_bar_alternating_direction() {
    let mut sampler = RunBarSampler::new(5);

    // Alternating buy/sell should never emit bar
    for i in 0..20 {
        let price = if i % 2 == 0 {
            100.0 + (i as f64 * 0.01)
        } else {
            100.0 - (i as f64 * 0.01)
        };
        assert!(sampler.update(price, 10.0, ts(1000 + i as i64)).is_none());
    }
}

#[test]
fn test_run_bar_performance_single_tick() {
    let mut sampler = RunBarSampler::new(1000);

    let start = Instant::now();
    sampler.update(100.0, 10.0, ts(1000));
    let elapsed = start.elapsed();

    // Must be <50μs per tick
    assert!(
        elapsed.as_micros() < 50,
        "Single tick took {}μs (target: <50μs)",
        elapsed.as_micros()
    );
}

#[test]
fn test_run_bar_performance_100_ticks() {
    let mut sampler = RunBarSampler::new(1000);

    let start = Instant::now();
    for i in 0..100 {
        sampler.update(100.0 + (i as f64 * 0.01), 10.0, ts(1000 + i as i64));
    }
    let elapsed = start.elapsed();

    let avg_per_tick = elapsed.as_micros() / 100;
    assert!(
        avg_per_tick < 50,
        "Average per tick: {}μs (target: <50μs)",
        avg_per_tick
    );
}

#[test]
fn test_run_bar_tick_rule() {
    let mut sampler = RunBarSampler::new(5);

    // Test tick rule: price change determines direction
    // Up tick (price increase) = buy
    assert!(sampler.update(100.0, 10.0, ts(1000)).is_none());
    assert!(sampler.update(100.1, 10.0, ts(1001)).is_none()); // Buy
    assert!(sampler.update(100.2, 10.0, ts(1002)).is_none()); // Buy
    assert!(sampler.update(100.3, 10.0, ts(1003)).is_none()); // Buy
    let bar = sampler.update(100.4, 10.0, ts(1004)); // Buy

    assert!(bar.is_some());
    let bar = bar.unwrap();
    assert_eq!(bar.open, 100.0);
    assert_eq!(bar.close, 100.4);
}

#[test]
fn test_run_bar_reset_after_emission() {
    let mut sampler = RunBarSampler::new(3);

    // First bar: 3 buys
    assert!(sampler.update(100.0, 10.0, ts(1000)).is_none());
    assert!(sampler.update(100.1, 10.0, ts(1001)).is_none());
    let bar = sampler.update(100.2, 10.0, ts(1002));
    assert!(bar.is_some());

    // After emission, counter should be reset
    // Next 2 buys should not emit bar
    assert!(sampler.update(100.3, 10.0, ts(1003)).is_none());
    assert!(sampler.update(100.4, 10.0, ts(1004)).is_none());

    // 3rd buy should emit new bar
    let bar = sampler.update(100.5, 10.0, ts(1005));
    assert!(bar.is_some());
    assert_eq!(bar.unwrap().open, 100.3); // New bar starts after reset
}

#[test]
fn test_run_bar_sampler_getters() {
    let mut sampler = RunBarSampler::new(50);

    assert_eq!(sampler.threshold(), 50);
    assert_eq!(sampler.run_count(), 0);
    assert_eq!(sampler.direction(), 0);

    // After one buy tick
    sampler.update(100.0, 10.0, ts(1000));
    sampler.update(100.1, 10.0, ts(1001));
    assert_eq!(sampler.run_count(), 2);
    assert_eq!(sampler.direction(), 1); // Buy direction
}

#[test]
fn test_run_bar_sampler_reset() {
    let mut sampler = RunBarSampler::new(5);

    sampler.update(100.0, 10.0, ts(1000));
    sampler.update(100.1, 10.0, ts(1001));

    assert_eq!(sampler.run_count(), 2);

    sampler.reset();
    assert_eq!(sampler.run_count(), 0);
    assert_eq!(sampler.direction(), 0);
}

#[test]
#[should_panic(expected = "Threshold must be greater than 0")]
fn test_run_bar_zero_threshold() {
    RunBarSampler::new(0);
}
