mod app;
mod buffer;
mod flags;
mod input;
mod layout;
mod render;
mod search;

use std::io::IsTerminal;

use clap::Parser;

fn main() -> anyhow::Result<()> {
    let mut flags = flags::Flags::parse();
    if let Ok(bundle) = std::env::var("LESS") {
        flags.merge_env_bundle(&bundle);
    }

    let path = flags.files.first().map(String::as_str);
    let source = input::Source::open(path)?;
    let mut buf = buffer::LineBuffer::new(source);

    let screen_rows = if std::io::stdout().is_terminal() {
        crossterm::terminal::size().ok().map(|(_, rows)| rows as usize)
    } else {
        None
    };

    let Some(rows) = screen_rows else {
        buf.fill_all()?;
        return app::dump(&buf);
    };

    if flags.quit_if_one_screen {
        buf.fill_to(rows + 1)?;
        if buf.eof() && buf.len() <= rows {
            return app::dump(&buf);
        }
    }

    buf.fill_all()?;
    app::run(flags, buf)
}
