use std::process::ExitCode;
use std::time::Duration;

use clap::Parser;

use digit::protocol::finger;
use digit::query::{Query, DEFAULT_PORT};

/// digit - a finger protocol client (RFC 1288 / RFC 742)
///
/// Query user information from finger servers. Supports standard queries,
/// user listings, and forwarding chains.
///
/// Note: Forwarding queries (user@host1@host2) depend on server support.
/// Many modern finger servers disable forwarding for security reasons.
#[derive(Parser, Debug)]
#[command(version, about)]
struct Cli {
    /// Finger query (e.g. "user@host", "@host", "user@host1@host2")
    query: Option<String>,

    /// Request verbose/long output (sends /W)
    #[arg(short, long)]
    long: bool,

    /// Port to connect on
    #[arg(short, long, default_value_t = DEFAULT_PORT)]
    port: u16,

    /// Connection timeout in seconds
    #[arg(short, long, default_value_t = 10)]
    timeout: u64,
}

fn main() -> ExitCode {
    let cli = Cli::parse();

    let query = Query::parse(cli.query.as_deref(), cli.long, cli.port);
    let timeout = Duration::from_secs(cli.timeout);

    match finger(&query, timeout) {
        Ok(response) => {
            print!("{}", response);
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("digit: {}", e);
            ExitCode::FAILURE
        }
    }
}
