#![warn(clippy::pedantic)]
//! Redcell is a markup language used to represent hemolymph card text.
//!
//! It is a subset of markdown. Hemolinks work as \[markdown\](links), and sagas are lists enumerated with plus signs (`+`).
//!
//! This module has a parser parses for Redcell into `RedellString`s, an AST that can be used in multiple contexts. Currently, Hemolymph uses them to show clickable Hemolinks. In the future, Redcell will also have markup that'll be used in cards' typst templates.

use serde::Deserialize;
use serde::Serialize;
use std::{
    error::Error,
    fmt::{Display, Write},
    ops::RangeInclusive,
};

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
/// An element of a `RichString`.
pub enum RedcellNode {
    String(String),
    /// A hemolink
    CardSearch {
        /// What is shown
        display: String,
        /// Query
        search: String,
    },
    Saga(Vec<RedcellString>),
    LineBreak,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Default)]
/// A vec of `RichElement`s.
pub struct RedcellString {
    pub elements: Vec<RedcellNode>,
}

impl RedcellString {
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.elements.is_empty()
    }
    /// Convert to a raw, unformatted string.
    #[must_use]
    pub fn to_raw(&self) -> String {
        let mut result = String::new();

        for el in &self.elements {
            match el {
                RedcellNode::String(string) => result += string,
                RedcellNode::CardSearch { display, .. } => result += display,
                RedcellNode::Saga(rich_strings) => {
                    for el in rich_strings {
                        writeln!(&mut result, "+ {}", el.to_raw())
                            .expect("Write impl on strings is infallible.");
                    }
                }
                RedcellNode::LineBreak => result.push('\n'),
            }
        }

        result
    }
    /// Convert to redcell text.
    #[must_use]
    pub fn to_redcell(&self) -> String {
        let mut result = String::new();

        for el in &self.elements {
            match el {
                RedcellNode::String(string) => result += string,
                RedcellNode::CardSearch { display, search } => {
                    write!(&mut result, "[{display}]({search})")
                        .expect("Write impl on strings is infallible.");
                }
                RedcellNode::Saga(rich_strings) => {
                    for el in rich_strings {
                        // result += &format!("+ {}\n", el.to_redcell())
                        writeln!(&mut result, "+ {}", el.to_redcell())
                            .expect("Write impl on strings is infallible.");
                    }
                }
                RedcellNode::LineBreak => result.push('\n'),
            }
        }

        result
    }
}

#[derive(Debug)]
pub enum ParseErr {
    IncompleteHemolinkBody { starts_at: usize },
    IncompleteHemolinkLink { starts_at: usize },
    HemolinkMissingLink { range: RangeInclusive<usize> },
    EscapedWrong { escaped: Option<char> },
}

impl Display for ParseErr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::IncompleteHemolinkBody { starts_at } => {
                write!(f, "Hemolink body was ended prematurely at byte {starts_at}")
            }
            Self::IncompleteHemolinkLink { starts_at } => {
                write!(f, "Hemolink link was ended prematurely at byte {starts_at}")
            }
            Self::HemolinkMissingLink { range } => {
                write!(
                    f,
                    "Hemolink link was ended without a link at bytes {}..={}",
                    range.start(),
                    range.end()
                )
            }
            Self::EscapedWrong { escaped } => match escaped {
                Some(char) => write!(f, "Tried to escape a `{char:?}` character."),
                None => write!(f, "Expecting escaped character, but file ended."),
            },
        }
    }
}

impl Error for ParseErr {}

/// The state the parser, defining the things that are expected of the syntax.
#[derive(Default)]
enum ParserState {
    /// Just text. Ended by anything that would be understood as not-just-raw-text.
    #[default]
    String,
    /// The body of a Hemolink.
    HemolinkBody { starts_at: usize },
    /// We are waiting for a Hemolink's link.
    HemolinkAwaitLink {
        display: String,
        display_at: RangeInclusive<usize>,
    },
    /// The link of a Hemolink
    HemolinkLink { display: String, starts_at: usize },
}

/// The parser itself, defining a few things not directly related to the syntax nodes expected.
#[derive(Default)]
struct Parser {
    /// The main register contains the elements at the current level of nesting. If `in_saga_line` is false, we are not at the top level.
    main_reg: Vec<RedcellNode>,
    /// The side register contains the elements at the level of nesting above. If `in_saga_line` is true, this register contains the top level. If it is false, this is empty.
    side_reg: Vec<RedcellNode>,
    /// Escape the next character.
    escape: bool,
    /// Current string to be added to whatever we're currently parsing.
    current_string: String,

    /// Are we in a saga line? If this is true, `main_reg` contains the current nesting level and `side_reg` contains the top level. Otherwise, `main_reg` is the top level and this is empty.
    ///
    /// Normally we'd use a stack for nested structures, but since the nesting always has
    /// a depth of one I don't want to deal with stacking.
    in_saga_line: bool,

    /// What are we expecting to consume?
    state: ParserState,
}

impl Parser {
    /// Ends a line. This can mean that \n has been consumed, or that the end of the file has been reached properly (that is, in the Start state). To differentiate those two cases, `eof` is used. If it is false, it inserts a line break.
    fn end_line(mut self, eof: bool) -> Self {
        if !self.current_string.is_empty() {
            self.main_reg.push(RedcellNode::String(self.current_string));
            self.current_string = String::new();
        }

        if self.in_saga_line {
            // If we're in a saga line, that means string and saga_string have been swapped.
            // We swap them back se we can work with saga_string as the inner nesting level.
            std::mem::swap(&mut self.main_reg, &mut self.side_reg);
            self.in_saga_line = false;
            if let Some(RedcellNode::String(thing)) = self.side_reg.first_mut() {
                *thing = thing.trim_start().to_string();
            }
            if let Some(RedcellNode::Saga(ongoing)) = self.main_reg.last_mut() {
                ongoing.push(RedcellString {
                    elements: self.side_reg,
                });
            } else {
                self.main_reg.push(RedcellNode::Saga(vec![RedcellString {
                    elements: self.side_reg,
                }]));
            }
            self.side_reg = vec![];
        } else if !eof {
            self.main_reg.push(RedcellNode::LineBreak);
        }
        self
    }
}

/// Parse a string as Redcell into a `RichString`.
/// # Errors
/// If the string isn't correct Redcell.
#[allow(clippy::too_many_lines)]
pub fn parse(text: &str) -> Result<RedcellString, ParseErr> {
    let text = text.char_indices().filter(|(_, x)| *x != '\r');

    let mut parser = Parser::default();

    for (idx, char) in text {
        // FUCK this character and Windows.
        if char == '\r' {
            continue;
        }
        match parser.state {
            ParserState::String => match char {
                '[' if !parser.escape => {
                    if !parser.current_string.is_empty() {
                        parser
                            .main_reg
                            .push(RedcellNode::String(parser.current_string));
                        parser.current_string = String::new();
                    }
                    parser.state = ParserState::HemolinkBody { starts_at: idx };
                }
                '\\' if !parser.escape => {
                    parser.escape = true;
                }
                '\n' => {
                    // If we're escaping this thing I'm going to assume you forgot something or just REALLY like typst.
                    if parser.escape {
                        return Err(ParseErr::EscapedWrong {
                            escaped: Some('\n'),
                        });
                    }

                    parser = parser.end_line(false);
                }
                // If we're at the beginning of a line and not already building a saga line,
                // a plus sign begins a saga line.
                '+' if !parser.escape && !parser.in_saga_line => {
                    if parser.current_string.trim().is_empty()
                        && parser.main_reg.last().is_none_or(|x| {
                            matches!(x, RedcellNode::LineBreak | RedcellNode::Saga(_))
                        })
                    {
                        // Line was already empty anyways, but it might have spaces.
                        parser.current_string = String::new();

                        // We nest to the lower level.
                        std::mem::swap(&mut parser.main_reg, &mut parser.side_reg);

                        parser.in_saga_line = true;
                    } else {
                        parser.current_string.push(char);
                        parser.escape = false;
                    }
                }
                _ => {
                    parser.current_string.push(char);
                    parser.escape = false;
                }
            },
            ParserState::HemolinkBody { starts_at } => match char {
                ']' if !parser.escape => {
                    parser.state = ParserState::HemolinkAwaitLink {
                        display: parser.current_string,
                        display_at: starts_at..=idx,
                    };
                    parser.current_string = String::new();
                }
                '\\' if !parser.escape => {
                    parser.escape = true;
                }
                _ => {
                    parser.current_string.push(char);
                    parser.escape = false;
                }
            },
            ParserState::HemolinkAwaitLink { ref display, .. } => match char {
                '(' => {
                    parser.state = ParserState::HemolinkLink {
                        display: display.to_string(),
                        starts_at: idx,
                    }
                }
                char if char.is_whitespace() => (),
                _ => (),
            },
            ParserState::HemolinkLink { ref display, .. } => match char {
                ')' if !parser.escape => {
                    parser.main_reg.push(RedcellNode::CardSearch {
                        display: display.to_string(),
                        search: parser.current_string.trim().to_string(),
                    });
                    parser.current_string = String::new();
                    parser.state = ParserState::String;
                }
                '\\' if !parser.escape => {
                    parser.escape = true;
                }
                char => {
                    parser.current_string.push(char);
                    parser.escape = false;
                }
            },
        }
    }

    if parser.escape {
        return Err(ParseErr::EscapedWrong { escaped: None });
    }

    match parser.state {
        ParserState::String => parser = parser.end_line(true),
        ParserState::HemolinkBody { starts_at } => {
            return Err(ParseErr::IncompleteHemolinkBody { starts_at });
        }
        ParserState::HemolinkAwaitLink { display_at, .. } => {
            return Err(ParseErr::HemolinkMissingLink { range: display_at });
        }
        ParserState::HemolinkLink { starts_at, .. } => {
            return Err(ParseErr::IncompleteHemolinkLink { starts_at });
        }
    }

    Ok(RedcellString {
        elements: parser.main_reg,
    })
}

#[cfg(test)]
mod tests {
    //! # Structure of a test
    //! These tests consist of:
    //! - An input string that will be parsed. These must use exclusively Unix-style line breaks.
    //! - An expected output manually constructed in Rust.
    //!
    //! The input is parsed into redcell and we assert that the output is equal to the expected output.
    //! A second comparison is made, replacing all instances of `\n` in the input for `\n\r` and parsing that. We assert that the output is equal to the same expected output.
    //!
    //! Then, the expected output (which, at this point, we know is correct) is converted back into a string. We assert that it's equal to the original input string.
    //!
    //! # When to make a new test
    //! There are two situations when a test must be made:
    //! - A new feature is added.
    //! - A bug is found. If the bug is found through a bug report, the report should be linked as a doc comment on the test. This helps prevent regressions.

    use super::*;

    #[test]
    fn simple_line() {
        let input = "this is an example text.";
        let expected = RedcellString {
            elements: vec![RedcellNode::String(input.to_string())],
        };

        assert_eq!(expected, parse(input).unwrap(), "Unix version");
        assert_eq!(
            expected,
            parse(&input.replace('\n', "\n\r")).unwrap(),
            "Windows version"
        );

        assert_eq!(expected.to_redcell(), input);
    }

    #[test]
    fn multiline() {
        let input = "this is an example text.\nwith multiple lines.";
        let expected = RedcellString {
            elements: vec![
                RedcellNode::String("this is an example text.".to_string()),
                RedcellNode::LineBreak,
                RedcellNode::String("with multiple lines.".to_string()),
            ],
        };

        assert_eq!(expected, parse(input).unwrap(), "Unix version");
        assert_eq!(
            expected,
            parse(&input.replace('\n', "\n\r")).unwrap(),
            "Windows version"
        );

        assert_eq!(expected.to_redcell(), input);
    }

    #[test]
    fn hemolink() {
        let input = "this has a [hemolink](thing) in the middle";
        let expected = RedcellString {
            elements: vec![
                RedcellNode::String("this has a ".to_string()),
                RedcellNode::CardSearch {
                    display: "hemolink".to_string(),
                    search: "thing".to_string(),
                },
                RedcellNode::String(" in the middle".to_string()),
            ],
        };

        assert_eq!(expected, parse(input).unwrap(), "Unix version");
        assert_eq!(
            expected,
            parse(&input.replace('\n', "\n\r")).unwrap(),
            "Windows version"
        );

        assert_eq!(expected.to_redcell(), input);
    }

    #[test]
    fn hemolink_in_newline() {
        let input = "this has a line.\nand a newline with a [hemolink](thing).";
        let expected = RedcellString {
            elements: vec![
                RedcellNode::String("this has a line.".to_string()),
                RedcellNode::LineBreak,
                RedcellNode::String("and a newline with a ".to_string()),
                RedcellNode::CardSearch {
                    display: "hemolink".to_string(),
                    search: "thing".to_string(),
                },
                RedcellNode::String(".".to_string()),
            ],
        };

        assert_eq!(expected, parse(input).unwrap(), "Unix version");
        assert_eq!(
            expected,
            parse(&input.replace('\n', "\n\r")).unwrap(),
            "Windows version"
        );

        assert_eq!(expected.to_redcell(), input);
    }

    #[test]
    fn saga() {
        let input = "this has a line\n+ and a saga\n+ with stuff\n";
        let expected = RedcellString {
            elements: vec![
                RedcellNode::String("this has a line".to_string()),
                RedcellNode::LineBreak,
                RedcellNode::Saga(vec![
                    RedcellString {
                        elements: vec![RedcellNode::String("and a saga".to_string())],
                    },
                    RedcellString {
                        elements: vec![RedcellNode::String("with stuff".to_string())],
                    },
                ]),
            ],
        };

        assert_eq!(expected, parse(input).unwrap(), "Unix version");
        assert_eq!(
            expected,
            parse(&input.replace('\n', "\n\r")).unwrap(),
            "Windows version"
        );

        assert_eq!(expected.to_redcell(), input);
    }
}
