use reqwest::Client;

mod puzzle;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

    let client = Client::new();
    
    let response = client.get("http://localhost:3006/")
        .send()
        .await?;

    let cookie = &response.headers().get("Set-Cookie").unwrap().clone();

    let puzzle: puzzle::Puzzle = response.json::<puzzle::RequestPuzzle>()
        .await?
        .into();


    match puzzle.solve().and_then(|p| p.into_response()) {
        Some(solution) => {
            match serde_json::to_string(&solution) {
                Ok(solution) => {
                    let response = client.post("http://localhost:3006/")
                        .body(solution)
                        .header("Cookie", cookie)
                        .send()
                        .await?;


                    let bytes = response.bytes().await.unwrap();
                    let bytes_string = std::str::from_utf8(&bytes).unwrap();
                    println!("{}", bytes_string);
                },
                Err(err) => panic!("{:?}", err)
            }
        },
        None => panic!("no solution found")
    }

    

    Ok(())

}
