#[cfg(feature = "cli")]
mod cli {
    use clap::{Parser, Subcommand};
    use lunchflow::{LunchFlowClient, Result, TransactionParams};

    #[derive(Parser)]
    #[command(name = "lunchflow", about = "LunchFlow API CLI", version)]
    struct Cli {
        /// LunchFlow API key (or set LUNCHFLOW_API_KEY)
        #[arg(long, env = "LUNCHFLOW_API_KEY")]
        api_key: String,

        #[command(subcommand)]
        command: Command,
    }

    #[derive(Subcommand)]
    enum Command {
        /// List all accounts
        Accounts,

        /// Get the balance for an account
        Balance {
            /// Account ID
            account_id: u64,
        },

        /// Get transactions for an account
        Transactions {
            /// Account ID
            account_id: u64,

            /// Include pending transactions
            #[arg(long)]
            pending: bool,

            /// Start date (YYYY-MM-DD, inclusive)
            #[arg(long)]
            from: Option<String>,

            /// End date (YYYY-MM-DD, inclusive)
            #[arg(long)]
            to: Option<String>,
        },

        /// Get holdings for an account
        Holdings {
            /// Account ID
            account_id: u64,
        },
    }

    pub async fn run() -> Result<()> {
        let cli = Cli::parse();
        let client = LunchFlowClient::new(cli.api_key)?;

        match cli.command {
            Command::Accounts => {
                let accounts = client.list_accounts().await?;
                for a in &accounts {
                    println!(
                        "{:>8}  {:<30}  {:<20}  {}  {}",
                        a.id,
                        a.name,
                        a.institution_name,
                        a.currency.as_deref().unwrap_or("-"),
                        a.status
                    );
                }
                println!("\n{} account(s)", accounts.len());
            }

            Command::Balance { account_id } => {
                let balance = client.get_balance(account_id).await?;
                println!("{} {:.2}", balance.currency, balance.amount);
            }

            Command::Transactions {
                account_id,
                pending,
                from,
                to,
            } => {
                let params = TransactionParams {
                    include_pending: pending,
                    from,
                    to,
                };
                let txns = client.get_transactions(account_id, params).await?;
                for t in &txns {
                    let pending_marker = if t.is_pending { " (pending)" } else { "" };
                    let desc = t
                        .merchant
                        .as_deref()
                        .or(t.description.as_deref())
                        .unwrap_or("-");
                    println!(
                        "{}  {:>10.2} {}  {}{}",
                        t.date, t.amount, t.currency, desc, pending_marker
                    );
                }
                println!("\n{} transaction(s)", txns.len());
            }

            Command::Holdings { account_id } => {
                let h = client.get_holdings(account_id).await?;
                for holding in &h.holdings {
                    let ticker = holding.security.ticker_symbol.as_deref().unwrap_or("N/A");
                    println!(
                        "{:<6}  {:<30}  qty {:>10.4}  @ {:>10.2}  = {:>12.2} {}",
                        ticker,
                        holding.security.name,
                        holding.quantity,
                        holding.price,
                        holding.value,
                        holding.currency,
                    );
                }
                println!("\nTotal: {:.2} {}", h.total_value, h.currency);
            }
        }

        Ok(())
    }
}

#[tokio::main]
async fn main() {
    #[cfg(feature = "cli")]
    {
        if let Err(e) = cli::run().await {
            eprintln!("error: {e}");
            std::process::exit(1);
        }
    }

    #[cfg(not(feature = "cli"))]
    {
        eprintln!("Compiled without the 'cli' feature. Rebuild with --features cli.");
        std::process::exit(1);
    }
}
