

use chrono::Utc;
use chrono_tz::US::Eastern;

/// CLI app to expose some useful functions from ncaa_data_rs
use clap::{
    Parser,
    Subcommand,
};

use ncaa_data_rs::ncaa::{
    query::scoreboard,
    sports::supported_sports,
    scoreboard::Scoreboard,
};

#[derive(Parser)]
#[clap(author = "Evan Flynn", version, about, long_about = None)]
struct Cli {
    // Sport to search for
    pub sport: String,  // TODO(flynneva): pre-populate supported sports as options?
    pub gender: String,
    pub division: String,
    #[clap(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    List {
        // List todays games
        #[clap(short, long, action)]
        games_today: bool,
    }
}

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let cli = Cli::parse();

    let sport = cli.sport;
    let gender = cli.gender;
    let division = cli.division;
    let mut full_sport = "".to_string();

    let possible_sports = supported_sports();

    // Confirm given sport is supported
    assert!(possible_sports.iter().any(|s| s.name == sport));

    // Get sport struct for the selected sport
    let _this_sport = &possible_sports[0];
    for s in &possible_sports {
        if s.name == sport {
            let _this_sport = s;
            // TODO: some sports do not have variations (football, softball)
            // so gender is not always required via CLI.
            // Figure out way to only ask for gender if sport requires it
            // Get correct variation based on gender
            if let Some(variations) = &s.variations {
                for variation in variations {
                    if variation.contains(&gender) {
                        full_sport = format!("{}{}", &s.name, &variation);
                        break
                    }
                }
                if full_sport.is_empty() {
                    panic!("Gender for sport not found: {}", &gender);
                }
            } else {
                println!("Sport `{}` does not have any variations, ignoring gender", &s.name);
                full_sport = s.name.to_string();
                break
            }
        }
    }

    match &cli.command {
        Commands::List { games_today } => {
            if *games_today {
                println!("List todays games for {}", full_sport);
                let current_date = Utc::now().with_timezone(&Eastern);
                let formatted_date = _this_sport.get_date_str(current_date).unwrap();
                let todays_scoreboard: Scoreboard = scoreboard(&full_sport, &division, &formatted_date).await.unwrap();
                println!("{}", todays_scoreboard);
            } else {
                println!("No option specified for list subcommand");
            }
        }
    }

    Ok(())
}
