use std::thread::sleep;
use std::time::{Duration, Instant};

use color_eyre::eyre::ContextCompat;
use console::Term;
use nix_output::action;
use nix_output::state::State;

fn main() -> Result<(), color_eyre::Report> {
    color_eyre::install().unwrap();
    let mut args = std::env::args().skip(1);
    let first = args.next().context("Failed to get first arg")?;

    let lines = std::fs::read_to_string(first)?;
    let mut state = State::new(Term::stderr().size().1);
    let start = Instant::now();
    for line in lines.lines() {
        let mut time = line.split("~");
        let instant = time.next().unwrap(); // impossible to fail
        let instant: u128 = instant.parse()?;
        let elapsed = start.elapsed().as_millis();
        if instant > elapsed {
            sleep(Duration::from_millis(instant.saturating_sub(elapsed) as u64));
        }

        let line = time.collect::<String>();
        let line = line.strip_prefix("@nix ").unwrap_or(&line);
        let action = action::Action::parse(line)?;
        state.handle(&action)?;
    }

    Ok(())
}
