use altimate_core::lineage::column_lineage;
use altimate_core::schema::types::SqlDialect;
use std::collections::HashMap;

fn main() {
    let sql = r#"WITH facts_173 AS (
SELECT TO_TIMESTAMP(TT_CREATED_TS) AS event_ts,
       GUID::VARCHAR AS entity_230,
       BUTTON_ORDERS AS fact_269,
       BINARY_BUTTON_ORDER AS fact_270
FROM (SELECT tt_created_ts, guid, orders,
      CASE WHEN application_subtype = 'Toolbar' THEN orders ELSE 0 END AS button_orders,
      CASE WHEN application_subtype = 'Toolbar' THEN 1 ELSE 0 end as binary_button_order
      FROM summary.shopping_order_cube_v6)
),
fact_summaries AS (
  SELECT TO_DATE(event_ts) AS date,
         entity_230 AS subject,
         SUM(fact_269) AS aggregation_value
  FROM facts_173
  GROUP BY 1, 2
)
SELECT date, COALESCE(SUM(aggregation_value), 0) AS aggregation_value
FROM fact_summaries
GROUP BY 1"#;

    let schema: HashMap<String, serde_json::Value> = serde_json::from_str(r#"{
        "SHOPPING_ORDER_CUBE_V6": {"TT_CREATED_TS": "VARCHAR", "GUID": "VARCHAR", "ORDERS": "VARCHAR", "APPLICATION_SUBTYPE": "VARCHAR", "BUTTON_ORDERS": "VARCHAR", "BINARY_BUTTON_ORDER": "VARCHAR"}
    }"#).unwrap();

    let result = column_lineage(sql, SqlDialect::Snowflake, &schema, None).unwrap();
    eprintln!("=== Output ===");
    let mut keys: Vec<_> = result.column_dict.keys().collect();
    keys.sort();
    for k in keys {
        let mut srcs: Vec<_> = result.column_dict[k].iter().collect();
        srcs.sort();
        eprintln!("  {}: {:?}", k, srcs);
    }

    eprintln!("\n=== Expected ===");
    eprintln!("  AGGREGATION_VALUE: GUID, ORDERS");
    eprintln!("  DATE: TT_CREATED_TS");

    let agg = result.column_dict.get("AGGREGATION_VALUE");
    if let Some(srcs) = agg {
        let has_orders = srcs.iter().any(|s| s.contains("ORDERS"));
        let has_guid = srcs.iter().any(|s| s.contains("GUID"));
        eprintln!("\n  Has ORDERS: {}", has_orders);
        eprintln!("  Has GUID: {}", has_guid);
    }
}
