//! Translation context for IR to SQL conversion.
//!
//! The `TranslationContext` carries state through the translation process,
//! including the function registry and accumulated CTEs.

use std::collections::HashMap;

use ordermap::OrderMap;

use hamelin_lib::func::def::FunctionTranslationContext;
use hamelin_lib::sql::expression::identifier::SimpleIdentifier;
use hamelin_lib::sql::query::SQLQuery;
use hamelin_translation::IRExpression;

use crate::TranslationRegistry;

/// Translation context - carries state through translation.
///
/// This context is passed through the translation process and accumulates
/// CTEs as they are processed.
#[derive(Debug)]
pub struct TranslationContext<'a> {
    /// The function translation registry
    pub registry: &'a TranslationRegistry,

    /// Accumulated CTEs (ordered - later CTEs can reference earlier ones)
    pub ctes: OrderMap<SimpleIdentifier, SQLQuery>,

    /// Function translation context (window, specials_allowed, order_by)
    /// Set by command layer when translating expressions within AGG/WINDOW commands.
    pub fctx: FunctionTranslationContext,

    /// Script-level scalar `DEF` bindings — bare identifier references inline these expressions.
    pub scalar_def_bindings: HashMap<String, IRExpression>,
}

impl<'a> TranslationContext<'a> {
    /// Create a new translation context with the given registry.
    pub fn new(registry: &'a TranslationRegistry) -> Self {
        Self {
            registry,
            ctes: OrderMap::new(),
            fctx: FunctionTranslationContext::default(),
            scalar_def_bindings: HashMap::new(),
        }
    }

    /// Add a CTE to the context.
    pub fn add_cte(&mut self, name: SimpleIdentifier, query: SQLQuery) {
        self.ctes.insert(name, query);
    }
}
