use std::io::IsTerminal;
use std::sync::OnceLock;

pub const GREEN: &str = "\x1b[32m";
pub const RED: &str = "\x1b[31m";
pub const YELLOW: &str = "\x1b[33m";
pub const CYAN: &str = "\x1b[36m";
pub const BOLD: &str = "\x1b[1m";
pub const DIM: &str = "\x1b[2m";
pub const RESET: &str = "\x1b[0m";

static STDOUT_IS_TTY: OnceLock<bool> = OnceLock::new();
static STDERR_IS_TTY: OnceLock<bool> = OnceLock::new();
static JSON_ONLY: OnceLock<bool> = OnceLock::new();

pub fn stdout_is_tty() -> bool {
    *STDOUT_IS_TTY.get_or_init(|| std::io::stdout().is_terminal())
}
pub fn stderr_is_tty() -> bool {
    *STDERR_IS_TTY.get_or_init(|| std::io::stderr().is_terminal())
}
pub fn set_json_only(v: bool) {
    let _ = JSON_ONLY.set(v);
}
pub fn json_only() -> bool {
    *JSON_ONLY.get().unwrap_or(&false)
}

pub fn strip_ansi(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\x1b' && chars.peek() == Some(&'[') {
            chars.next();
            for c2 in chars.by_ref() {
                if c2.is_ascii_alphabetic() {
                    break;
                }
            }
            continue;
        }
        out.push(c);
    }
    out
}

pub fn ok(msg: impl std::fmt::Display) {
    if stdout_is_tty() {
        println!("{GREEN}{BOLD}OK:{RESET} {msg}");
    } else {
        println!("OK: {}", strip_ansi(&msg.to_string()));
    }
}
pub fn err(msg: impl std::fmt::Display) {
    if stderr_is_tty() {
        eprintln!("{RED}{BOLD}ERROR:{RESET} {msg}");
    } else {
        eprintln!("ERROR: {}", strip_ansi(&msg.to_string()));
    }
}
pub fn warn(msg: impl std::fmt::Display) {
    if json_only() { return; }
    if stderr_is_tty() {
        eprintln!("{YELLOW}{BOLD}WARN:{RESET} {msg}");
    } else {
        eprintln!("WARN: {}", strip_ansi(&msg.to_string()));
    }
}
pub fn hint(msg: impl std::fmt::Display) {
    if stderr_is_tty() {
        eprintln!("{DIM}Hint:{RESET} {msg}");
    } else {
        eprintln!("Hint: {}", strip_ansi(&msg.to_string()));
    }
}
pub fn note(msg: impl std::fmt::Display) {
    if json_only() { return; }
    if stdout_is_tty() {
        println!("{CYAN}{msg}{RESET}");
    } else {
        println!("{}", strip_ansi(&msg.to_string()));
    }
}