use ruff_diagnostics::Applicability;
use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::{self as ast, BoolOp, CmpOp, Expr};

use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::side_effect;
use ruff_python_ast::token::parenthesized_range;
use ruff_text_size::Ranged;

use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};

/// ## What it does
/// Checks for unnecessary key checks prior to accessing a dictionary.
///
/// ## Why is this bad?
/// When working with dictionaries, the `get` can be used to access a value
/// without having to check if the dictionary contains the relevant key,
/// returning `None` if the key is not present.
///
/// ## Example
/// ```python
/// if "key" in dct and dct["key"]:
///     ...
/// ```
///
/// Use instead:
/// ```python
/// if dct.get("key"):
///     ...
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as safe, unless the expression contains comments
/// or may have side effects.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.2.0")]
pub(crate) struct UnnecessaryKeyCheck;

impl AlwaysFixableViolation for UnnecessaryKeyCheck {
    #[derive_message_formats]
    fn message(&self) -> String {
        "Unnecessary key check before dictionary access".to_string()
    }

    fn fix_title(&self) -> String {
        "Replace with `dict.get`".to_string()
    }
}

/// RUF019
pub(crate) fn unnecessary_key_check(checker: &Checker, expr: &Expr) {
    if !checker.semantic().in_boolean_test() {
        return;
    }

    let Expr::BoolOp(ast::ExprBoolOp {
        op: BoolOp::And,
        values,
        ..
    }) = expr
    else {
        return;
    };

    let [left, right] = values.as_slice() else {
        return;
    };

    // Left should be, e.g., `key in dct`.
    let Expr::Compare(ast::ExprCompare {
        left: key_left,
        ops,
        comparators,
        ..
    }) = left
    else {
        return;
    };

    if !matches!(&**ops, [CmpOp::In]) {
        return;
    }

    let [obj_left] = &**comparators else {
        return;
    };

    // Right should be, e.g., `dct[key]`.
    let Expr::Subscript(ast::ExprSubscript {
        value: obj_right,
        slice: key_right,
        ..
    }) = right
    else {
        return;
    };

    if ComparableExpr::from(obj_left) != ComparableExpr::from(obj_right)
        || ComparableExpr::from(key_left) != ComparableExpr::from(key_right)
    {
        return;
    }

    let obj_effect = side_effect(obj_left, |id| checker.semantic().has_builtin_binding(id));
    let key_effect = side_effect(key_left, |id| checker.semantic().has_builtin_binding(id));
    let combined = obj_effect.merge(key_effect);
    if combined.is_present() {
        return;
    }

    let mut diagnostic = checker.report_diagnostic(UnnecessaryKeyCheck, expr.range());

    let applicability =
        if !combined.is_absent() || checker.comment_ranges().intersects(expr.range()) {
            Applicability::Unsafe
        } else {
            Applicability::Safe
        };

    diagnostic.set_fix(Fix::applicable_edit(
        Edit::range_replacement(
            format!(
                "{}.get({})",
                checker.locator().slice(
                    parenthesized_range(obj_right.into(), right.into(), checker.tokens(),)
                        .unwrap_or(obj_right.range())
                ),
                checker.locator().slice(
                    parenthesized_range(key_right.into(), right.into(), checker.tokens(),)
                        .unwrap_or(key_right.range())
                ),
            ),
            expr.range(),
        ),
        applicability,
    ));
}
