use crate::parser::ast::{Stmt, Expr};

pub fn is_extend_or_include_call(stmt: &Stmt) -> bool {
    match stmt {
        Stmt::ImportSo { .. } => true,
        Stmt::Assignment { right, .. } => is_extend_or_include_expr(right),
        Stmt::ExprStmt { expr, .. } => is_extend_or_include_expr(expr),
        Stmt::AssignmentDestructure { right, .. } => is_extend_or_include_expr(right),
        Stmt::AssignmentScoped { right, .. } => is_extend_or_include_expr(right),
    }
}
pub fn is_extend_or_include_expr(expr: &Expr) -> bool {
    match expr {
        Expr::FunctionCall { callee, .. } => {
            match &**callee {
                Expr::Ident { name, .. } if name == "extend" || name == "include" => true,
                _ => false,
            }
        }
        _ => false,
    }
}

pub fn is_printing_function_stmt(stmt: &Stmt) -> bool {
    match stmt {
        Stmt::ExprStmt { expr, .. } => match expr {
            Expr::FunctionCall { callee, .. } => match &**callee {
                Expr::Ident { name, .. } => name == "slog" || name == "sput",
                _ => false,
            },
            _ => false,
        },
        _ => false,
    }
}

pub fn is_input_complete(src: &str) -> bool {
    let mut paren = 0;
    let mut bracket = 0;
    let mut brace = 0;
    let mut in_single = false;
    let mut in_double = false;
    let mut in_backtick = false;
    let mut escaped = false;
    for ch in src.chars() {
        if in_single {
            if !escaped && ch == '\'' {
                in_single = false;
            }
            escaped = ch == '\\' && !escaped;
            continue;
        }
        if in_double {
            if !escaped && ch == '"' {
                in_double = false;
            }
            escaped = ch == '\\' && !escaped;
            continue;
        }
        if in_backtick {
            if !escaped && ch == '`' {
                in_backtick = false;
            }
            escaped = ch == '\\' && !escaped;
            continue;
        }
        match ch {
            '(' => paren += 1,
            ')' => if paren > 0 { paren -= 1; },
            '[' => bracket += 1,
            ']' => if bracket > 0 { bracket -= 1; },
            '{' => brace += 1,
            '}' => if brace > 0 { brace -= 1; },
            '\'' => in_single = true,
            '"' => in_double = true,
            '`' => in_backtick = true,
            _ => (),
        }
        escaped = ch == '\\' && !escaped;
    }
    paren == 0 && bracket == 0 && brace == 0 && !in_single && !in_double && !in_backtick
}
