use altimate_core::lineage::polyglot_column_lineage;
use altimate_core::schema::types::SqlDialect;
use std::io::BufRead;
use std::path::Path;

#[derive(serde::Deserialize)]
struct Case {
    #[allow(dead_code)]
    name: String,
    sql: String,
    expected: std::collections::HashMap<String, Vec<String>>,
}

fn main() {
    let fixture_path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/lineage/snowflake_ground_truth.jsonl");
    let file = std::fs::File::open(&fixture_path).expect("open");
    let reader = std::io::BufReader::with_capacity(1024 * 1024, file);
    let dialect = SqlDialect::Snowflake;

    let mut total = 0u64;
    let mut zero_edges = 0u64;
    let mut zero_edges_with_expected = 0u64;
    let mut total_missing_from_zero = 0u64;
    let mut polyglot_errors = 0u64;

    for line in reader.lines() {
        let line = line.unwrap();
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let case: Case = match serde_json::from_str(line) {
            Ok(c) => c,
            Err(_) => continue,
        };
        total += 1;

        match polyglot_column_lineage(&case.sql, dialect) {
            Err(_) => {
                polyglot_errors += 1;
            }
            Ok(result) => {
                if result.edges.is_empty() {
                    zero_edges += 1;
                    if !case.expected.is_empty() {
                        zero_edges_with_expected += 1;
                        total_missing_from_zero += case.expected.len() as u64;
                    }
                }
            }
        }
    }

    println!("Total queries: {total}");
    println!("Polyglot errors: {polyglot_errors}");
    println!("Zero edges: {zero_edges}");
    println!("Zero edges with non-empty expected: {zero_edges_with_expected}");
    println!("Total expected cols from zero-edge queries: {total_missing_from_zero}");
}
