use anyhow::{Context, Result};
use momentry_core::core::db::{Database, PostgresDb};
use std::env;

#[tokio::main]
async fn main() -> Result<()> {
    env::set_var("RUST_LOG", "info");

    println!("=== BM25 簡單測試 ===\n");

    // 初始化 PostgreSQL
    let pg = PostgresDb::init()
        .await
        .context("Failed to initialize PostgreSQL database")?;

    // 測試查詢
    let test_queries = vec![
        ("telephone", Some("384b0ff44aaaa1f1")),
        ("工作", Some("9760d0820f0cf9a7")),
        ("团体", Some("9760d0820f0cf9a7")), // Simplified Chinese, should match Traditional "團體"
        ("computer", None),
    ];

    for (query_str, uuid_opt) in test_queries {
        println!(
            "\n🔍 測試查詢: '{}' {}",
            query_str,
            uuid_opt
                .map(|u| format!("(uuid: {})", u))
                .unwrap_or_default()
        );

        // 顯示轉換後的 tsquery (除錯用)
        match pg.prepare_tsquery(query_str).await {
            Ok(tsquery) => println!("  TSQUERY: {}", tsquery),
            Err(e) => println!("  TSQUERY 錯誤: {}", e),
        }

        let results = pg.search_bm25(query_str, uuid_opt, 5).await?;

        println!("找到 {} 筆結果:", results.len());
        for (i, r) in results.iter().enumerate() {
            let text_preview: String = r.text.chars().take(60).collect();
            let text_preview = if r.text.chars().count() > 60 {
                format!("{}...", text_preview)
            } else {
                text_preview
            };
            println!(
                "  {}. {} (uuid: {}, chunk_id: {})",
                i + 1,
                text_preview,
                r.uuid,
                r.chunk_id
            );
            println!(
                "     分數: {:.4}, 時間: {:.1}-{:.1}s, 類型: {}",
                r.bm25_score, r.start_time, r.end_time, r.chunk_type
            );
        }

        if results.is_empty() {
            println!("  ⚠️  沒有找到結果");
        }
    }

    Ok(())
}
