//! Polyglot bindings: transpile, format_sql, extract_metadata, compare_queries.

use pyo3::prelude::*;

/// Transpile SQL from one dialect to another.
#[pyfunction]
pub fn transpile(py: Python<'_>, sql: &str, source: &str, target: &str) -> PyResult<PyObject> {
    let start = std::time::Instant::now();
    let s = crate::convert::parse_dialect(source)?;
    let t = crate::convert::parse_dialect(target)?;
    let result = altimate_core::polyglot::transpile(sql, s, t);
    crate::sdk::timed_emit("transpile", start);
    crate::convert::to_py_result(py, &result)
}

/// Format / pretty-print SQL for a dialect.
#[pyfunction]
#[pyo3(signature = (sql, dialect="generic"))]
pub fn format_sql(py: Python<'_>, sql: &str, dialect: &str) -> PyResult<PyObject> {
    let start = std::time::Instant::now();
    let d = crate::convert::parse_dialect(dialect)?;
    let result = altimate_core::polyglot::format_sql(sql, d);
    crate::sdk::timed_emit_with_dialect("formatSql", dialect, start);
    crate::convert::to_py_result(py, &result)
}

/// Extract metadata (tables, columns, functions) from SQL.
#[pyfunction]
#[pyo3(signature = (sql, dialect="generic"))]
pub fn extract_metadata(py: Python<'_>, sql: &str, dialect: &str) -> PyResult<PyObject> {
    let start = std::time::Instant::now();
    let d = crate::convert::parse_dialect(dialect)?;
    let result = altimate_core::polyglot::extract_metadata(sql, d)
        .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e))?;
    crate::sdk::timed_emit_with_dialect("extractMetadata", dialect, start);
    crate::convert::to_py_result(py, &result)
}

/// Extract the output column names from a SQL SELECT list.
#[pyfunction]
#[pyo3(signature = (sql, dialect="generic"))]
pub fn extract_output_columns(py: Python<'_>, sql: &str, dialect: &str) -> PyResult<PyObject> {
    let start = std::time::Instant::now();
    let d = crate::convert::parse_dialect(dialect)?;
    let result = altimate_core::polyglot::extract_output_columns(sql, d)
        .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e))?;
    crate::sdk::timed_emit_with_dialect("extractOutputColumns", dialect, start);
    crate::convert::to_py_result(py, &result)
}

/// Compare two SQL queries structurally.
#[pyfunction]
#[pyo3(signature = (left_sql, right_sql, dialect="generic"))]
pub fn compare_queries(
    py: Python<'_>,
    left_sql: &str,
    right_sql: &str,
    dialect: &str,
) -> PyResult<PyObject> {
    let start = std::time::Instant::now();
    let d = crate::convert::parse_dialect(dialect)?;
    let result = altimate_core::polyglot::compare_queries(left_sql, right_sql, d)
        .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e))?;
    crate::sdk::timed_emit_with_dialect("compareQueries", dialect, start);
    crate::convert::to_py_result(py, &result)
}
