//! Bridge between polyglot-sql lineage types and altimate-core's format.
//!
//! Converts `ColumnLineageEdge` into the `"table"."column"` qualified
//! reference format used by the Python `ColumnLineageComplete` tests.

use crate::schema::types::SqlDialect;
use polyglot_sql::lineage::ColumnLineageEdge;

/// Convert a [`ColumnLineageEdge`] into a qualified `"table"."column"` string.
///
/// The format matches the Python `ColumnLineageComplete` output:
/// - For simple tables: `"table1"."a"`
/// - For 3-part names: `"db"."schema"."table1"."a"`
/// - For Snowflake: all identifiers are uppercased
pub fn edge_to_qualified_ref(edge: &ColumnLineageEdge, dialect: SqlDialect) -> String {
    let table = &edge.source_table;
    let col = &edge.source_column;

    // Build the qualified reference with quoting
    let parts: Vec<&str> = table.split('.').collect();
    let mut qualified = parts
        .iter()
        .map(|p| format!("\"{}\"", p))
        .collect::<Vec<_>>();
    qualified.push(format!("\"{}\"", col));

    let result = qualified.join(".");

    match dialect {
        SqlDialect::Snowflake => result.to_uppercase(),
        _ => result,
    }
}

/// Normalize an output column name for dialect-aware comparison.
pub fn normalize_column_name(name: &str, dialect: SqlDialect) -> String {
    match dialect {
        SqlDialect::Snowflake => name.to_uppercase(),
        _ => name.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use polyglot_sql::lineage::{ColumnLineageEdge, LensType, TerminalKind};

    fn make_edge(table: &str, col: &str, target: &str) -> ColumnLineageEdge {
        ColumnLineageEdge {
            source_table: table.to_string(),
            source_column: col.to_string(),
            target_column: target.to_string(),
            edge_type: "direct".to_string(),
            lens_type: LensType::Unchanged,
            lens_code: vec![],
            terminal_kind: TerminalKind::Table,
        }
    }

    #[test]
    fn simple_ref() {
        let edge = make_edge("table1", "a", "a");
        assert_eq!(
            edge_to_qualified_ref(&edge, SqlDialect::Generic),
            "\"table1\".\"a\""
        );
    }

    #[test]
    fn three_part_ref() {
        let edge = make_edge("db.schema.table1", "a", "a");
        assert_eq!(
            edge_to_qualified_ref(&edge, SqlDialect::Generic),
            "\"db\".\"schema\".\"table1\".\"a\""
        );
    }

    #[test]
    fn snowflake_uppercase() {
        let edge = make_edge("table1", "a", "a");
        assert_eq!(
            edge_to_qualified_ref(&edge, SqlDialect::Snowflake),
            "\"TABLE1\".\"A\""
        );
    }
}
