use anyhow::Result;
use clap::Parser;
use std::io::IsTerminal;
use std::path::PathBuf;
use std::str::FromStr;
use excel_cli::app;
use excel_cli::excel;
use excel_cli::json_export;
use excel_cli::ui;
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
#[arg(required = true)]
file_path: PathBuf,
#[arg(long, short = 'j')]
json_export: bool,
#[arg(long, short = 'd', default_value = "h")]
direction: String,
#[arg(long, short = 'r', default_value = "1")]
header_count: usize,
#[arg(long, short = 'l')]
lazy_loading: bool,
}
fn main() -> Result<()> {
let cli = Cli::parse();
if !std::io::stdout().is_terminal() && !cli.json_export {
eprintln!("Excel-cli error: Pipe detected but -j or --json-export flag not provided.");
std::process::exit(1);
}
let workbook = excel::open_workbook(&cli.file_path, cli.lazy_loading)?;
if cli.json_export {
let Ok(direction) = json_export::HeaderDirection::from_str(&cli.direction) else {
anyhow::bail!("Invalid header direction: {}", cli.direction)
};
let all_sheets =
json_export::generate_all_sheets_json(&workbook, direction, cli.header_count)?;
let json_string = json_export::serialize_to_json(&all_sheets)?;
println!("{json_string}");
return Ok(());
}
let app_state = app::AppState::new(workbook, cli.file_path)?;
ui::run_app(app_state)?;
Ok(())
}