use std::{
    fs::File,
    io::{BufRead, BufReader},
    process::ExitCode,
};

use pukram2html::{Settings, TextInfo, convert_extended};

fn main() -> ExitCode {
    let mut args = std::env::args();
    args.next();
    let Some(in_path) = args.next() else {
        eprintln!("No input path specified");
        return ExitCode::FAILURE;
    };
    let Some(out_path) = args.next() else {
        eprintln!("No output path specified");
        return ExitCode::FAILURE;
    };

    let in_file = match File::open(&in_path) {
        Ok(file) => file,
        Err(e) => {
            eprintln!("Error opening input file: {e}");
            return ExitCode::FAILURE;
        }
    };
    let mut out_file = match File::create(&out_path) {
        Ok(file) => file,
        Err(e) => {
            eprintln!("Error creating output file: {e}");
            return ExitCode::FAILURE;
        }
    };

    let mut use_textboxes = false;
    for arg in args {
        if arg == "box" {
            use_textboxes = true;
        } else {
            eprintln!("Invalid argument {arg}");
            eprintln!("Use one of these arguments: 'box'");
            return ExitCode::FAILURE;
        }
    }

    let TextInfo {
        lines,
        words,
        chars,
    } = convert_extended(
        BufReader::new(in_file)
            .lines()
            .map(Result::unwrap_or_default),
        &mut out_file,
        Settings::default().with_use_textboxes(use_textboxes),
    );

    println!("{lines} {words} {chars}");

    ExitCode::SUCCESS
}
