#![feature(let_chains)]

use std::collections::{HashSet, VecDeque};

use stuff::{
    autocomplete,
    readline::{Buffer, NonEmptyVec, Readline, ReadlineProvider},
};

#[derive(Default)]
struct P {
    history: VecDeque<String>,
}

impl ReadlineProvider for P {
    fn completions(&mut self, buffer: &Buffer) -> Option<NonEmptyVec<String>> {
        let word_before_cursor = buffer.word_before_cursor();
        let is_first = buffer.is_first_word();

        let mut entries = HashSet::new();
        if let Some(word) = word_before_cursor
            && !is_first
        {
            autocomplete::complete_from_cwd(&mut entries, word, &Default::default());
        } else {
            let prefix = word_before_cursor.unwrap_or("");
            autocomplete::complete_binary_from_env(&mut entries, prefix);
        }

        let mut entries = NonEmptyVec::try_from_iter(entries.drain()).ok()?;
        entries.sort();

        Some(entries)
    }

    fn push_history(&mut self, entry: &str) {
        self.history.push_back(entry.into());
    }

    fn lookup_history(&mut self, depth: usize) -> Option<String> {
        if depth >= self.history.len() {
            return None;
        }
        let index = self.history.len() - depth - 1;
        Some(self.history[index].clone())
    }
}

fn main() {
    logsink::setup_logging(true);
    let mut readline = Readline::new(P::default()).unwrap();

    loop {
        let Some(line) = readline.readline().unwrap() else {
            break;
        };
        println!("{line:?}");
        if line == "exit" {
            break;
        }
    }
}
