// use crate::process::{LErr, Trace};
use crate::lexer::Token;
use crate::validator::VErr;
use chumsky::prelude::*;

const SEPARATOR: &str = "\n\n***\n";

fn line_number(src: &'static str, span: SimpleSpan) -> usize {
    src.chars().take(span.start).filter(|c| *c == '\n').count()
}

fn get_line(src: &'static str, line: usize) -> String {
    src.split("\n").nth(line).unwrap().to_string()
}

pub fn lexing(errs: Vec<Rich<'static, char>>) -> String {
    let mut msg = "Syntax errors".to_string();
    for err in errs {
        msg = format!("{msg}\n{:#?}", err);
    }
    msg
}

pub fn validation(errs: Vec<VErr>) -> String {
    let mut msgs = vec![];
    for err in errs {
        let mut msg = vec![];
        let line_number = line_number(err.src, *err.span);
        let line = get_line(err.src, line_number);
        msg.push(format!("Validation error: {}", err.msg));
        msg.push(format!("  on line {} in {}", line_number + 1, err.input));
        msg.push(format!("  >>> {line}"));
        msgs.push(msg.join("\n"));
    }
    msgs.join(SEPARATOR)
}

pub fn parsing(errs: Vec<Rich<'static, Token>>) -> String {
    let mut msg = "Syntax errors".to_string();
    for err in errs {
        msg = format!("{msg}\n{:#?}", err);
    }
    msg
}
