use itertools::Itertools;
use syntax::{
    Edition, NodeOrToken, SyntaxNode, SyntaxToken, T,
    ast::{self, AstNode, syntax_factory::SyntaxFactory},
    match_ast,
    syntax_editor::{Position, SyntaxEditor},
};

use crate::{AssistContext, AssistId, Assists};

// Assist: remove_dbg
//
// Removes `dbg!()` macro call.
//
// ```
// fn main() {
//     let x = $0dbg!(42 * dbg!(4 + 2));$0
// }
// ```
// ->
// ```
// fn main() {
//     let x = 42 * (4 + 2);
// }
// ```
pub(crate) fn remove_dbg(acc: &mut Assists, ctx: &AssistContext<'_, '_>) -> Option<()> {
    let (editor, _) = SyntaxEditor::new(ctx.source_file().syntax().clone());
    let make = editor.make();
    let macro_calls = if ctx.has_empty_selection() {
        vec![ctx.find_node_at_offset::<ast::MacroExpr>()?]
    } else {
        ctx.covering_element()
            .as_node()?
            .descendants()
            .filter(|node| ctx.selection_trimmed().contains_range(node.text_range()))
            // When the selection exactly covers the macro call to be removed, `covering_element()`
            // returns `ast::MacroCall` instead of its parent `ast::MacroExpr` that we want. So
            // first try finding `ast::MacroCall`s and then retrieve their parent.
            .filter_map(ast::MacroCall::cast)
            .filter_map(|it| it.syntax().parent().and_then(ast::MacroExpr::cast))
            .collect()
    };

    let replacements = macro_calls
        .into_iter()
        .filter_map(|macro_expr| compute_dbg_replacement(macro_expr, make))
        .collect::<Vec<_>>();
    let target = replacements
        .iter()
        .flat_map(|(node_or_token, _)| node_or_token.iter())
        .map(|t| t.text_range())
        .reduce(|acc, range| acc.cover(range))?;
    acc.add(AssistId::quick_fix("remove_dbg"), "Remove dbg!()", target, |builder| {
        for (range, expr) in replacements {
            if let Some(expr) = expr {
                editor.insert(Position::before(range[0].clone()), expr.syntax());
            }
            for node_or_token in range {
                editor.delete(node_or_token);
            }
        }
        builder.add_file_edits(ctx.vfs_file_id(), editor);
    })
}

/// Returns `None` when either
/// - macro call is not `dbg!()`
/// - any node inside `dbg!()` could not be parsed as an expression
/// - (`macro_expr` has no parent - is that possible?)
///
/// Returns `Some(_, None)` when the macro call should just be removed.
fn compute_dbg_replacement(
    macro_expr: ast::MacroExpr,
    make: &SyntaxFactory,
) -> Option<(Vec<NodeOrToken<SyntaxNode, SyntaxToken>>, Option<ast::Expr>)> {
    let macro_call = macro_expr.macro_call()?;
    let tt = macro_call.token_tree()?;
    let r_delim = NodeOrToken::Token(tt.right_delimiter_token()?);
    if macro_call.path()?.segment()?.name_ref()?.text() != "dbg"
        || macro_call.excl_token().is_none()
    {
        return None;
    }

    let mac_input = tt.syntax().children_with_tokens().skip(1).take_while(|it| *it != r_delim);
    let input_expressions = mac_input.chunk_by(|tok| tok.kind() == T![,]);
    let input_expressions = input_expressions
        .into_iter()
        .filter_map(|(is_sep, group)| (!is_sep).then_some(group))
        .map(|tokens| tokens.collect::<Vec<_>>())
        .filter(|tokens| !tokens.iter().all(|it| it.kind().is_trivia()))
        .map(|tokens| syntax::hacks::parse_expr_from_str(&tokens.iter().join(""), Edition::CURRENT))
        .collect::<Option<Vec<ast::Expr>>>()?;

    let parent = macro_expr.syntax().parent()?;
    Some(match &*input_expressions {
        // dbg!()
        [] => {
            match_ast! {
                match parent {
                    ast::StmtList(_) => {
                        let mut replace = vec![macro_expr.syntax().clone().into()];
                        if let Some(prev_sibling) = macro_expr.syntax().prev_sibling_or_token()
                            && prev_sibling.kind() == syntax::SyntaxKind::WHITESPACE {
                                replace.push(prev_sibling);
                        }
                        (replace, None)
                    },
                    ast::ExprStmt(it) => {
                        let mut replace = vec![it.syntax().clone().into()];
                        if let Some(prev_sibling) = it.syntax().prev_sibling_or_token()
                            && prev_sibling.kind() == syntax::SyntaxKind::WHITESPACE {
                                replace.push(prev_sibling);
                        }
                        (replace, None)
                    },
                    _ => (vec![macro_call.syntax().clone().into()], Some(make.expr_unit())),
                }
            }
        }
        // dbg!(2, 'x', &x, x, ...);
        exprs if ast::ExprStmt::can_cast(parent.kind()) && exprs.iter().all(pure_expr) => {
            let mut replace = vec![parent.clone().into()];
            if let Some(prev_sibling) = parent.prev_sibling_or_token()
                && prev_sibling.kind() == syntax::SyntaxKind::WHITESPACE
            {
                replace.push(prev_sibling);
            }
            (replace, None)
        }
        // dbg!(expr0)
        [expr] => {
            // dbg!(expr, &parent);
            let wrap = match ast::Expr::cast(parent) {
                Some(parent) => match (expr, parent) {
                    (ast::Expr::CastExpr(_), ast::Expr::CastExpr(_)) => false,
                    (
                        ast::Expr::PrefixExpr(_) | ast::Expr::RefExpr(_) | ast::Expr::MacroExpr(_),
                        ast::Expr::AwaitExpr(_)
                        | ast::Expr::CallExpr(_)
                        | ast::Expr::CastExpr(_)
                        | ast::Expr::FieldExpr(_)
                        | ast::Expr::IndexExpr(_)
                        | ast::Expr::MethodCallExpr(_)
                        | ast::Expr::RangeExpr(_)
                        | ast::Expr::TryExpr(_),
                    ) => true,
                    (
                        ast::Expr::BinExpr(_)
                        | ast::Expr::CastExpr(_)
                        | ast::Expr::RangeExpr(_)
                        | ast::Expr::MacroExpr(_),
                        ast::Expr::AwaitExpr(_)
                        | ast::Expr::BinExpr(_)
                        | ast::Expr::CallExpr(_)
                        | ast::Expr::CastExpr(_)
                        | ast::Expr::FieldExpr(_)
                        | ast::Expr::IndexExpr(_)
                        | ast::Expr::MethodCallExpr(_)
                        | ast::Expr::PrefixExpr(_)
                        | ast::Expr::RangeExpr(_)
                        | ast::Expr::RefExpr(_)
                        | ast::Expr::TryExpr(_),
                    ) => true,
                    _ => false,
                },
                None => false,
            };
            let expr = replace_nested_dbgs(expr.clone(), make);
            let expr = if wrap { make.expr_paren(expr).into() } else { expr };
            (vec![macro_call.syntax().clone().into()], Some(expr))
        }
        // dbg!(expr0, expr1, ...)
        exprs => {
            let exprs = exprs.iter().cloned().map(|expr| replace_nested_dbgs(expr, make));
            let expr = make.expr_tuple(exprs);
            (vec![macro_call.syntax().clone().into()], Some(expr.into()))
        }
    })
}

fn pure_expr(expr: &ast::Expr) -> bool {
    match_ast! {
        match (expr.syntax()) {
            ast::Literal(_) => true,
            ast::RefExpr(it) => {
                matches!(it.expr(), Some(ast::Expr::PathExpr(p))
                    if p.path().and_then(|p| p.as_single_name_ref()).is_some())
            },
            ast::PathExpr(it) => it.path().and_then(|it| it.as_single_name_ref()).is_some(),
            _ => false,
        }
    }
}

fn replace_nested_dbgs(expanded: ast::Expr, make: &SyntaxFactory) -> ast::Expr {
    if let ast::Expr::MacroExpr(mac) = &expanded {
        // Special-case when `expanded` itself is `dbg!()` since we cannot replace the whole tree
        // with `ted`. It should be fairly rare as it means the user wrote `dbg!(dbg!(..))` but you
        // never know how code ends up being!
        let replaced = if let Some((_, expr_opt)) = compute_dbg_replacement(mac.clone(), make) {
            match expr_opt {
                Some(expr) => expr,
                None => {
                    stdx::never!("dbg! inside dbg! should not be just removed");
                    expanded
                }
            }
        } else {
            expanded
        };

        return replaced;
    }

    let (editor, expanded) = SyntaxEditor::with_ast_node(&expanded);
    // We need to collect to avoid mutation during traversal.
    let macro_exprs: Vec<_> =
        expanded.syntax().descendants().filter_map(ast::MacroExpr::cast).collect();

    for mac in macro_exprs {
        let expr_opt = match compute_dbg_replacement(mac.clone(), make) {
            Some((_, expr)) => expr,
            None => continue,
        };

        if let Some(expr) = expr_opt {
            editor.replace(mac.syntax(), expr.syntax());
        } else {
            editor.delete(mac.syntax());
        }
    }
    let expanded_syntax = editor.finish().new_root().clone();
    ast::Expr::cast(expanded_syntax).unwrap()
}

#[cfg(test)]
mod tests {
    use crate::tests::{check_assist, check_assist_not_applicable};

    use super::*;

    fn check(
        #[rust_analyzer::rust_fixture] ra_fixture_before: &str,
        #[rust_analyzer::rust_fixture] ra_fixture_after: &str,
    ) {
        check_assist(
            remove_dbg,
            &format!("fn main() {{\n{ra_fixture_before}\n}}"),
            &format!("fn main() {{\n{ra_fixture_after}\n}}"),
        );
    }

    #[test]
    fn test_remove_dbg() {
        check("$0dbg!(1 + 1)", "1 + 1");
        check("dbg!$0(1 + 1)", "1 + 1");
        check("dbg!(1 $0+ 1)", "1 + 1");
        check("dbg![$01 + 1]", "1 + 1");
        check("dbg!{$01 + 1}", "1 + 1");
    }

    #[test]
    fn test_remove_simple_dbg_statement() {
        check_assist(
            remove_dbg,
            r#"
fn foo() {
    let n = 2;
    $0dbg!(3);
    dbg!(2.6);
    dbg!(1, 2.5);
    dbg!('x');
    dbg!(&n);
    dbg!(n);
    dbg!(n,);
    dbg!(n, );
    // needless comment
    dbg!("foo");$0
}
"#,
            r#"
fn foo() {
    let n = 2;
    // needless comment
}
"#,
        );
    }

    #[test]
    fn test_remove_trailing_comma_dbg() {
        check("$0dbg!(1 + 1,)", "1 + 1");
        check("$0dbg!(1 + 1, )", "1 + 1");
        check("$0dbg!(1 + 1,\n)", "1 + 1");
        check("$0dbg!(1 + 1, 2 + 3)", "(1 + 1, 2 + 3)");
        check("$0dbg!(1 + 1, 2 + 3 )", "(1 + 1, 2 + 3)");
        check("$0dbg!(1 + 1, 2 + 3, )", "(1 + 1, 2 + 3)");
        check("$0dbg!(1 + 1, 2 + 3 ,)", "(1 + 1, 2 + 3)");
    }

    #[test]
    fn test_remove_dbg_not_applicable() {
        check_assist_not_applicable(remove_dbg, "fn main() {$0vec![1, 2, 3]}");
        check_assist_not_applicable(remove_dbg, "fn main() {$0dbg(5, 6, 7)}");
        check_assist_not_applicable(remove_dbg, "fn main() {$0dbg!(5, 6, 7}");
    }

    #[test]
    fn test_remove_dbg_keep_semicolon_in_let() {
        // https://github.com/rust-lang/rust-analyzer/issues/5129#issuecomment-651399779
        check(
            r#"let res = $0dbg!(1 * 20); // needless comment"#,
            r#"let res = 1 * 20; // needless comment"#,
        );
        check(r#"let res = $0dbg!(); // needless comment"#, r#"let res = (); // needless comment"#);
        check(
            r#"let res = $0dbg!(1, 2); // needless comment"#,
            r#"let res = (1, 2); // needless comment"#,
        );
    }

    #[test]
    fn test_remove_dbg_cast_cast() {
        check(r#"let res = $0dbg!(x as u32) as u32;"#, r#"let res = x as u32 as u32;"#);
    }

    #[test]
    fn test_remove_dbg_prefix() {
        check(r#"let res = $0dbg!(&result).foo();"#, r#"let res = (&result).foo();"#);
        check(r#"let res = &$0dbg!(&result);"#, r#"let res = &&result;"#);
        check(r#"let res = $0dbg!(!result) && true;"#, r#"let res = !result && true;"#);
    }

    #[test]
    fn test_remove_dbg_post_expr() {
        check(r#"let res = $0dbg!(fut.await).foo();"#, r#"let res = fut.await.foo();"#);
        check(r#"let res = $0dbg!(result?).foo();"#, r#"let res = result?.foo();"#);
        check(r#"let res = $0dbg!(foo as u32).foo();"#, r#"let res = (foo as u32).foo();"#);
        check(r#"let res = $0dbg!(array[3]).foo();"#, r#"let res = array[3].foo();"#);
        check(r#"let res = $0dbg!(tuple.3).foo();"#, r#"let res = tuple.3.foo();"#);
    }

    #[test]
    fn test_remove_dbg_range_expr() {
        check(r#"let res = $0dbg!(foo..bar).foo();"#, r#"let res = (foo..bar).foo();"#);
        check(r#"let res = $0dbg!(foo..=bar).foo();"#, r#"let res = (foo..=bar).foo();"#);
    }

    #[test]
    fn test_remove_empty_dbg() {
        check_assist(remove_dbg, r#"fn foo() { $0dbg!(); }"#, r#"fn foo() { }"#);
        check_assist(
            remove_dbg,
            r#"
fn foo() {
    $0dbg!();
}
"#,
            r#"
fn foo() {
}
"#,
        );
        check_assist(
            remove_dbg,
            r#"
fn foo() {
    let test = $0dbg!();
}"#,
            r#"
fn foo() {
    let test = ();
}"#,
        );
        check_assist(
            remove_dbg,
            r#"
fn foo() {
    let t = {
        println!("Hello, world");
        $0dbg!()
    };
}"#,
            r#"
fn foo() {
    let t = {
        println!("Hello, world");
    };
}"#,
        );
    }

    #[test]
    fn test_remove_multi_dbg() {
        check(r#"$0dbg!(0, 1)"#, r#"(0, 1)"#);
        check(r#"$0dbg!(0, (1, 2))"#, r#"(0, (1, 2))"#);
    }

    #[test]
    fn test_range() {
        check(
            r#"
fn f() {
    dbg!(0) + $0dbg!(1);
    dbg!(())$0
}
"#,
            r#"
fn f() {
    dbg!(0) + 1;
    ()
}
"#,
        );
    }

    #[test]
    fn test_range_partial() {
        check_assist_not_applicable(remove_dbg, r#"$0dbg$0!(0)"#);
        check_assist_not_applicable(remove_dbg, r#"$0dbg!(0$0)"#);
    }

    #[test]
    fn test_nested_dbg() {
        check(
            r#"$0let x = dbg!(dbg!(dbg!(dbg!(0 + 1)) * 2) + dbg!(3));$0"#,
            r#"let x = ((0 + 1) * 2) + 3;"#,
        );
        check(r#"$0dbg!(10, dbg!(), dbg!(20, 30))$0"#, r#"(10, (), (20, 30))"#);
    }

    #[test]
    fn test_multiple_nested_dbg() {
        check(
            r#"
fn f() {
    $0dbg!();
    let x = dbg!(dbg!(dbg!(0 + 1)) + 2) + dbg!(3);
    dbg!(10, dbg!(), dbg!(20, 30));$0
}
"#,
            r#"
fn f() {
    let x = ((0 + 1) + 2) + 3;
    (10, (), (20, 30));
}
"#,
        );
    }
}
