//! Tool bindings: complete, rewrite, generate_tests, analyze_migration, parse_dbt_project.

use crate::schema::Schema;
use pyo3::prelude::*;

/// SQL completion engine: suggest tables, columns, functions, keywords at cursor position.
#[pyfunction]
pub fn complete(
    py: Python<'_>,
    sql: &str,
    cursor_pos: usize,
    schema: &Schema,
) -> PyResult<PyObject> {
    let start = std::time::Instant::now();
    let result = altimate_core::completer::complete(sql, cursor_pos, &schema.inner);
    crate::sdk::timed_emit("complete", start);
    crate::convert::to_py_result(py, &result)
}

/// Suggest query rewrites and optimizations.
#[pyfunction]
pub fn rewrite(py: Python<'_>, sql: &str, schema: &Schema) -> PyResult<PyObject> {
    let start = std::time::Instant::now();
    let result = altimate_core::rewriter::rewrite(sql, &schema.inner);
    crate::sdk::timed_emit("rewrite", start);
    crate::convert::to_py_result(py, &result)
}

/// Generate test cases for a SQL query (boundary values, NULLs, edge cases).
#[pyfunction]
pub fn generate_tests(py: Python<'_>, sql: &str, schema: &Schema) -> PyResult<PyObject> {
    let start = std::time::Instant::now();
    let result = altimate_core::testgen::generate_tests(sql, &schema.inner);
    crate::sdk::timed_emit("generateTests", start);
    crate::convert::to_py_result(py, &result)
}

/// Analyze migration safety (data loss, type narrowing, missing defaults).
#[pyfunction]
pub fn analyze_migration(py: Python<'_>, sql: &str, schema: &Schema) -> PyResult<PyObject> {
    let start = std::time::Instant::now();
    let result = altimate_core::migration::analyze_migration(sql, &schema.inner);
    crate::sdk::timed_emit("analyzeMigration", start);
    crate::convert::to_py_result(py, &result)
}

/// Parse a dbt project directory.
#[pyfunction]
pub fn parse_dbt_project(py: Python<'_>, project_dir: &str) -> PyResult<PyObject> {
    let start = std::time::Instant::now();
    let result = altimate_core::dbt::parse_dbt_project(std::path::Path::new(project_dir))
        .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e))?;
    crate::sdk::timed_emit("parseDbtProject", start);
    crate::convert::to_py_result(py, &result)
}
