use std::iter::Peekable;

use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_notebook::CellOffsets;
use ruff_python_ast::token::{Token, TokenKind, Tokens};
use ruff_text_size::{Ranged, TextRange, TextSize};

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

/// ## What it does
/// Checks for files with multiple trailing blank lines.
///
/// In the case of notebooks, this check is applied to
/// each cell separately.
///
/// ## Why is this bad?
/// Trailing blank lines in a file are superfluous.
///
/// However, the last line of the file should end with a newline.
///
/// ## Example
/// ```python
/// spam(1)\n\n\n
/// ```
///
/// Use instead:
/// ```python
/// spam(1)\n
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.3.3")]
pub(crate) struct TooManyNewlinesAtEndOfFile {
    num_trailing_newlines: u32,
    in_notebook: bool,
}

impl AlwaysFixableViolation for TooManyNewlinesAtEndOfFile {
    #[derive_message_formats]
    fn message(&self) -> String {
        let domain = if self.in_notebook { "cell" } else { "file" };
        // We expect a single trailing newline; so two trailing newlines is one too many, three
        // trailing newlines is two too many, etc.
        if self.num_trailing_newlines > 2 {
            format!("Too many newlines at end of {domain}")
        } else {
            format!("Extra newline at end of {domain}")
        }
    }

    fn fix_title(&self) -> String {
        let title = if self.num_trailing_newlines > 2 {
            "Remove trailing newlines"
        } else {
            "Remove trailing newline"
        };
        title.to_string()
    }
}

/// W391
pub(crate) fn too_many_newlines_at_end_of_file(
    context: &LintContext,
    tokens: &Tokens,
    cell_offsets: Option<&CellOffsets>,
) {
    if let Some(cell_offsets) = cell_offsets {
        notebook_newline_diagnostics(tokens, cell_offsets, context);
    } else {
        let mut tokens_iter = tokens.iter().rev().peekable();
        newline_diagnostic(&mut tokens_iter, false, context);
    }
}

/// Collects trailing newline diagnostics for each cell
fn notebook_newline_diagnostics(
    tokens: &Tokens,
    cell_offsets: &CellOffsets,
    context: &LintContext,
) {
    let mut remaining_tokens = &tokens[..];

    for range in cell_offsets.content_ranges() {
        let start_index = remaining_tokens
            .iter()
            .position(|token| token.end() > range.start())
            .unwrap_or(remaining_tokens.len());
        remaining_tokens = &remaining_tokens[start_index..];

        let end_index = remaining_tokens
            .iter()
            .position(|token| token.start() >= range.end())
            .unwrap_or(remaining_tokens.len());
        let (cell_tokens, rest) = remaining_tokens.split_at(end_index);

        let mut tokens_iter = cell_tokens.iter().rev().peekable();
        newline_diagnostic(&mut tokens_iter, true, context);
        remaining_tokens = rest;
    }
}

/// Possible diagnostic, with fix, for too many newlines in cell or source file
fn newline_diagnostic<'a>(
    tokens_iter: &mut Peekable<impl Iterator<Item = &'a Token>>,
    in_notebook: bool,
    context: &LintContext,
) {
    let mut num_trailing_newlines: u32 = 0;
    let mut newline_range_start: Option<TextSize> = None;
    let mut newline_range_end: Option<TextSize> = None;

    while let Some(next_token) = tokens_iter.peek() {
        match next_token.kind() {
            TokenKind::Newline | TokenKind::NonLogicalNewline => {
                if newline_range_end.is_none() {
                    newline_range_end = Some(next_token.end());
                }
                newline_range_start = Some(next_token.end());

                tokens_iter.next();
                num_trailing_newlines += 1;
            }
            TokenKind::Dedent => {
                tokens_iter.next();
            }
            _ => {
                break;
            }
        }
    }

    if num_trailing_newlines == 0 || num_trailing_newlines == 1 {
        return;
    }

    let Some((start, end)) = (match (newline_range_start, newline_range_end) {
        (Some(s), Some(e)) => Some((s, e)),
        _ => None,
    }) else {
        return;
    };

    let diagnostic_range = TextRange::new(start, end);
    if let Some(mut diagnostic) = context.report_diagnostic_if_enabled(
        TooManyNewlinesAtEndOfFile {
            num_trailing_newlines,
            in_notebook,
        },
        diagnostic_range,
    ) {
        diagnostic.set_fix(Fix::safe_edit(Edit::range_deletion(diagnostic_range)));
    }
}
