// src/modules/repl/history.rs

use std::collections::VecDeque;
use std::fs::{OpenOptions, read_to_string};
use std::io::Write;
use std::path::PathBuf;
use std::env;

pub const HISTORY_LIMIT: usize = 500;

fn history_file_path() -> Option<PathBuf> {
    if let Ok(home) = env::var("HOME") {
        let mut p = PathBuf::from(home);
        p.push(".mumu_repl_history");
        Some(p)
    } else {
        None
    }
}

pub fn load_history() -> VecDeque<String> {
    let mut history = VecDeque::new();
    if let Some(path) = history_file_path() {
        if path.exists() {
            if let Ok(content) = read_to_string(&path) {
                for line in content.lines() {
                    let trimmed = line.trim_end();
                    if !trimmed.is_empty() {
                        history.push_back(trimmed.to_string());
                    }
                }
            }
        }
    }
    while history.len() > HISTORY_LIMIT {
        history.pop_front();
    }
    history
}

pub fn save_history_line(history: &mut VecDeque<String>, line: &str) {
    let trimmed = line.trim();
    if trimmed.is_empty() {
        return;
    }
    if let Some(last) = history.back() {
        if last == trimmed {
            return;
        }
    }
    history.push_back(trimmed.to_string());
    while history.len() > HISTORY_LIMIT {
        history.pop_front();
    }
    if let Some(path) = history_file_path() {
        if let Ok(mut f) = OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(path)
        {
            for entry in history.iter() {
                let _ = writeln!(f, "{}", entry);
            }
        }
    }
}
