mod api;
mod app;
mod calc;
mod config;
mod db;
mod screens;

use anyhow::Result;
use crossterm::event::{self, Event, KeyCode};
use ratatui::DefaultTerminal;
use sqlx::sqlite::SqlitePool;

use app::App;
use config::Settings;

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt::init();

    let settings = match config::load_settings() {
        Ok(s) => s,
        Err(e) => {
            eprintln!("Failed to load settings: {}", e);
            std::process::exit(1);
        }
    };

    if let Some(parent) = settings.db_path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    let pool = db::schema::init_pool(&settings.db_path).await?;
    db::schema::create_tables(&pool).await?;

    let mut terminal = ratatui::init();
    let result = run(&mut terminal, settings, pool).await;
    ratatui::restore();
    result
}

async fn run(terminal: &mut DefaultTerminal, settings: Settings, pool: SqlitePool) -> Result<()> {
    let mut app = App::new(settings, pool);

    loop {
        terminal.draw(|frame| app.render(frame))?;

        if let Event::Key(key) = event::read()? {
            if key.code == KeyCode::Char('q') {
                break;
            }
            app.handle_key(key);
        }
    }

    Ok(())
}
