// file: kb_lib/src/pair_candle_query.rs

//! Pair-candle query service.

/// Pair-candle query service.
///
/// Standard materialized timeframes are served from base storage.
/// Arbitrary timeframes are rebuilt on demand from `trade_events`.
#[derive(Debug, Clone)]
pub struct PairCandleQueryService {
    database: std::sync::Arc<crate::Database>,
}

impl PairCandleQueryService {
    /// Creates a new pair-candle query service.
    pub fn new(database: std::sync::Arc<crate::Database>) -> Self {
        return Self { database };
    }

    /// Lists candles for one pair and one timeframe.
    ///
    /// When `prefer_materialized` is true and the timeframe is standard,
    /// stored candles are returned when available. If no stored candle exists,
    /// candles are rebuilt on demand from `trade_events`.
    pub async fn list_pair_candles(
        &self,
        pair_id: i64,
        timeframe_seconds: i64,
        bucket_start_from: std::option::Option<i64>,
        bucket_start_to: std::option::Option<i64>,
        prefer_materialized: bool,
    ) -> Result<std::vec::Vec<crate::PairCandleDto>, crate::Error> {
        if timeframe_seconds <= 0 {
            return Err(crate::Error::InvalidState(format!(
                "invalid timeframe_seconds '{}'",
                timeframe_seconds
            )));
        }
        if prefer_materialized && is_materialized_timeframe(timeframe_seconds) {
            let candles_result = crate::query_pair_candles_list_by_pair_and_timeframe(
                self.database.as_ref(),
                pair_id,
                timeframe_seconds,
            )
            .await;
            let candles = match candles_result {
                Ok(candles) => candles,
                Err(error) => return Err(error),
            };
            let filtered_candles =
                filter_candles_by_bucket_range(candles, bucket_start_from, bucket_start_to);
            if !filtered_candles.is_empty() {
                return Ok(filtered_candles);
            }
        }
        let trade_events_result =
            crate::query_trade_events_list_by_pair_id(self.database.as_ref(), pair_id).await;
        let trade_events = match trade_events_result {
            Ok(trade_events) => trade_events,
            Err(error) => return Err(error),
        };
        let mut bucket_starts = std::collections::BTreeSet::<i64>::new();
        for trade_event in &trade_events {
            let event_time_option = crate::pair_candle_aggregation::extract_trade_event_unix_time(
                self.database.as_ref(),
                trade_event,
            )
            .await;
            let event_time_option = match event_time_option {
                Ok(event_time_option) => event_time_option,
                Err(error) => return Err(error),
            };
            let event_time_unix = match event_time_option {
                Some(event_time_unix) => event_time_unix,
                None => continue,
            };
            let bucket_start_result = crate::pair_candle_aggregation::bucket_start_unix(
                event_time_unix,
                timeframe_seconds,
            );
            let bucket_start_unix = match bucket_start_result {
                Ok(bucket_start_unix) => bucket_start_unix,
                Err(error) => return Err(error),
            };
            if let Some(bucket_start_from) = bucket_start_from {
                if bucket_start_unix < bucket_start_from {
                    continue;
                }
            }
            if let Some(bucket_start_to) = bucket_start_to {
                if bucket_start_unix > bucket_start_to {
                    continue;
                }
            }
            bucket_starts.insert(bucket_start_unix);
        }
        let mut candles = std::vec::Vec::new();
        for bucket_start_unix in bucket_starts {
            let candle_result = crate::pair_candle_aggregation::build_candle_from_trade_events(
                self.database.as_ref(),
                pair_id,
                timeframe_seconds,
                bucket_start_unix,
                &trade_events,
            )
            .await;
            let candle_option = match candle_result {
                Ok(candle_option) => candle_option,
                Err(error) => return Err(error),
            };
            if let Some(candle) = candle_option {
                candles.push(candle);
            }
        }
        return Ok(candles);
    }
}

fn is_materialized_timeframe(timeframe_seconds: i64) -> bool {
    return timeframe_seconds == 60
        || timeframe_seconds == 300
        || timeframe_seconds == 900
        || timeframe_seconds == 3600;
}

fn filter_candles_by_bucket_range(
    candles: std::vec::Vec<crate::PairCandleDto>,
    bucket_start_from: std::option::Option<i64>,
    bucket_start_to: std::option::Option<i64>,
) -> std::vec::Vec<crate::PairCandleDto> {
    let mut filtered = std::vec::Vec::new();
    for candle in candles {
        if let Some(bucket_start_from) = bucket_start_from {
            if candle.bucket_start_unix < bucket_start_from {
                continue;
            }
        }
        if let Some(bucket_start_to) = bucket_start_to {
            if candle.bucket_start_unix > bucket_start_to {
                continue;
            }
        }
        filtered.push(candle);
    }
    return filtered;
}

#[cfg(test)]
mod tests {
    async fn make_database() -> std::sync::Arc<crate::Database> {
        let tempdir_result = tempfile::tempdir();
        let tempdir = match tempdir_result {
            Ok(tempdir) => tempdir,
            Err(error) => panic!("tempdir must succeed: {}", error),
        };
        let database_path = tempdir.path().join("pair_candle_aggregation.sqlite3");
        let config = crate::DatabaseConfig {
            enabled: true,
            backend: crate::DatabaseBackend::Sqlite,
            sqlite: crate::SqliteDatabaseConfig {
                path: database_path.to_string_lossy().to_string(),
                create_if_missing: true,
                busy_timeout_ms: 5000,
                max_connections: 1,
                auto_initialize_schema: true,
                use_wal: true,
            },
        };
        let database_result = crate::Database::connect_and_initialize(&config).await;
        let database = match database_result {
            Ok(database) => database,
            Err(error) => panic!("database init must succeed: {}", error),
        };
        return std::sync::Arc::new(database);
    }

    async fn seed_fluxbeam_swap_transaction(
        database: std::sync::Arc<crate::Database>,
        signature: &str,
        block_time_unix: i64,
        base_amount_raw: &str,
        quote_amount_raw: &str,
    ) {
        let transaction_model = crate::TransactionModelService::new(database.clone());
        let dex_decode = crate::DexDecodeService::new(database.clone());
        let dex_detect = crate::DexDetectService::new(database.clone());
        let trade_aggregation = crate::TradeAggregationService::new(database.clone());
        let resolved_transaction = serde_json::json!({
            "slot": 960001,
            "blockTime": block_time_unix,
            "version": 0,
            "transaction": {
                "message": {
                    "instructions": [
                        {
                            "programId": crate::FLUXBEAM_PROGRAM_ID,
                            "program": "fluxbeam",
                            "stackHeight": 1,
                            "accounts": [
                                "CandlePool111",
                                "CandleLpMint111",
                                "CandleTokenA111",
                                crate::WSOL_MINT_ID
                            ],
                            "parsed": {
                                "info": {
                                    "instruction": "swap",
                                    "pool": "CandlePool111",
                                    "tokenA": "CandleTokenA111",
                                    "tokenB": crate::WSOL_MINT_ID,
                                    "baseAmountRaw": base_amount_raw,
                                    "quoteAmountRaw": quote_amount_raw
                                }
                            },
                            "data": "opaque"
                        }
                    ]
                }
            },
            "meta": {
                "err": null,
                "logMessages": [
                    "Program log: Instruction: Swap",
                    "Program log: buy"
                ]
            }
        });
        let project_result = transaction_model
            .persist_resolved_transaction(
                signature,
                Some("helius_primary_http".to_string()),
                &resolved_transaction,
            )
            .await;
        if let Err(error) = project_result {
            panic!("projection must succeed: {}", error);
        }
        let decode_result = dex_decode.decode_transaction_by_signature(signature).await;
        if let Err(error) = decode_result {
            panic!("dex decode must succeed: {}", error);
        }
        let detect_result = dex_detect.detect_transaction_by_signature(signature).await;
        if let Err(error) = detect_result {
            panic!("dex detect must succeed: {}", error);
        }
        let trade_result = trade_aggregation.record_transaction_by_signature(signature).await;
        if let Err(error) = trade_result {
            panic!("trade aggregation must succeed: {}", error);
        }
    }

    #[tokio::test]
    async fn list_pair_candles_can_rebuild_custom_timeframe_on_demand() {
        let database = make_database().await;
        seed_fluxbeam_swap_transaction(
            database.clone(),
            "sig-pair-candle-query-1",
            1_700_010_000,
            "1000",
            "2000",
        )
        .await;
        seed_fluxbeam_swap_transaction(
            database.clone(),
            "sig-pair-candle-query-2",
            1_700_010_020,
            "1000",
            "3000",
        )
        .await;
        seed_fluxbeam_swap_transaction(
            database.clone(),
            "sig-pair-candle-query-3",
            1_700_010_070,
            "1000",
            "1500",
        )
        .await;
        let trade_service = crate::PairCandleAggregationService::new(database.clone());
        let record_1 =
            trade_service.record_transaction_by_signature("sig-pair-candle-query-1").await;
        if let Err(error) = record_1 {
            panic!("candle aggregation 1 must succeed: {}", error);
        }
        let record_2 =
            trade_service.record_transaction_by_signature("sig-pair-candle-query-2").await;
        if let Err(error) = record_2 {
            panic!("candle aggregation 2 must succeed: {}", error);
        }
        let record_3 =
            trade_service.record_transaction_by_signature("sig-pair-candle-query-3").await;
        if let Err(error) = record_3 {
            panic!("candle aggregation 3 must succeed: {}", error);
        }
        let pools_result = crate::query_pools_list(database.as_ref()).await;
        let pools = match pools_result {
            Ok(pools) => pools,
            Err(error) => panic!("pool list must succeed: {}", error),
        };
        let pool_id = pools[0].id.unwrap_or_default();
        let pair_result = crate::query_pairs_get_by_pool_id(database.as_ref(), pool_id).await;
        let pair_option = match pair_result {
            Ok(pair_option) => pair_option,
            Err(error) => panic!("pair fetch must succeed: {}", error),
        };
        let pair = match pair_option {
            Some(pair) => pair,
            None => panic!("pair must exist"),
        };
        let pair_id = pair.id.unwrap_or_default();
        let query_service = crate::PairCandleQueryService::new(database);
        let candles_result = query_service.list_pair_candles(pair_id, 120, None, None, false).await;
        let candles = match candles_result {
            Ok(candles) => candles,
            Err(error) => panic!("custom candle query must succeed: {}", error),
        };
        assert_eq!(candles.len(), 1);
        assert_eq!(candles[0].open_price_quote_per_base, 2.0);
        assert_eq!(candles[0].high_price_quote_per_base, 3.0);
        assert_eq!(candles[0].low_price_quote_per_base, 1.5);
        assert_eq!(candles[0].close_price_quote_per_base, 1.5);
        assert_eq!(candles[0].trade_count, 3);
        assert_eq!(candles[0].base_volume_raw, Some("3000".to_string()));
        assert_eq!(candles[0].quote_volume_raw, Some("6500".to_string()));
    }

    #[tokio::test]
    async fn list_pair_candles_falls_back_when_materialized_storage_is_empty() {
        let database = make_database().await;
        seed_fluxbeam_swap_transaction(
            database.clone(),
            "sig-pair-candle-fallback-1",
            1_700_020_000,
            "1000",
            "2000",
        )
        .await;
        seed_fluxbeam_swap_transaction(
            database.clone(),
            "sig-pair-candle-fallback-2",
            1_700_020_010,
            "1000",
            "3000",
        )
        .await;
        let pools_result = crate::query_pools_list(database.as_ref()).await;
        let pools = match pools_result {
            Ok(pools) => pools,
            Err(error) => panic!("pool list must succeed: {}", error),
        };
        let pool_id = pools[0].id.unwrap_or_default();
        let pair_result = crate::query_pairs_get_by_pool_id(database.as_ref(), pool_id).await;
        let pair_option = match pair_result {
            Ok(pair_option) => pair_option,
            Err(error) => panic!("pair fetch must succeed: {}", error),
        };
        let pair = match pair_option {
            Some(pair) => pair,
            None => panic!("pair must exist"),
        };
        let pair_id = pair.id.unwrap_or_default();
        let materialized_result =
            crate::query_pair_candles_list_by_pair_and_timeframe(database.as_ref(), pair_id, 60)
                .await;
        let materialized = match materialized_result {
            Ok(materialized) => materialized,
            Err(error) => panic!("materialized candle list must succeed: {}", error),
        };
        assert_eq!(materialized.len(), 0);
        let query_service = crate::PairCandleQueryService::new(database);
        let candles_result = query_service.list_pair_candles(pair_id, 60, None, None, true).await;
        let candles = match candles_result {
            Ok(candles) => candles,
            Err(error) => panic!("fallback candle query must succeed: {}", error),
        };
        assert_eq!(candles.len(), 1);
        assert_eq!(candles[0].open_price_quote_per_base, 2.0);
        assert_eq!(candles[0].high_price_quote_per_base, 3.0);
        assert_eq!(candles[0].low_price_quote_per_base, 2.0);
        assert_eq!(candles[0].close_price_quote_per_base, 3.0);
        assert_eq!(candles[0].trade_count, 2);
    }
}
