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

fn main() {
    let sql = r#"SELECT cast(x.member_a AS int) as member_id,
       CONCAT('PayPal Email: ', cast(x.paypal_email AS string),
              '; Member B: ', cast(x.member_b AS string),
              ' (Email: ', cast(x.email AS string), ')',
              '; Diff Activity Month: ', cast(x.date_diff AS string)) as comp_values
FROM
  (SELECT a.member_id AS member_a,
          a.paypal_email,
          IFF(to_date(a.last_visit_date::VARCHAR, 'YYYYMMDD') = '1900-01-01',
              a.created_ts::date,
              to_date(a.last_visit_date::VARCHAR, 'YYYYMMDD')) as last_visit_member_a,
          b.member_id AS member_b,
          b.email,
          IFF(to_date(b.last_visit_date::VARCHAR, 'YYYYMMDD') = '1900-01-01',
              b.created_ts::date,
              to_date(b.last_visit_date::VARCHAR, 'YYYYMMDD')) as last_visit_member_b,
          case when b.member_id = FALSE and DATEDIFF('month', last_visit_member_b, last_visit_member_a) >= 36
              THEN -999 else DATEDIFF('month', last_visit_member_b, last_visit_member_a) end as date_diff
   FROM dw.member_profile a
   JOIN dw.member_profile b ON a.member_id != b.member_id
  ) X"#;

    let schema: HashMap<String, serde_json::Value> = serde_json::from_str(r#"{
        "MEMBER_PROFILE": {"MEMBER_ID": "VARCHAR", "EMAIL": "VARCHAR", "CREATED_TS": "VARCHAR", "PAYPAL_EMAIL": "VARCHAR", "LAST_VISIT_DATE": "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!("  COMP_VALUES: CREATED_TS, EMAIL, LAST_VISIT_DATE, MEMBER_ID, PAYPAL_EMAIL");
    eprintln!("  MEMBER_ID: MEMBER_ID");

    // Check
    let comp = result.column_dict.get("COMP_VALUES");
    if let Some(srcs) = comp {
        let has_created = srcs.iter().any(|s| s.contains("CREATED_TS"));
        let has_last_visit = srcs.iter().any(|s| s.contains("LAST_VISIT_DATE"));
        eprintln!("\n  Has CREATED_TS: {}", has_created);
        eprintln!("  Has LAST_VISIT_DATE: {}", has_last_visit);
    }
}
