// This example assumes that test items are defined in the dictionary in the following format.
// {
//    "tests": "itemcount, buttonsize",  # List of comma-separated test names.
//    "itemcount": {                     # Details of each test, including buckets and weight.
//        "buckets": [ "10", "15" ],
//        "weight": "1:1"
//    },
//    "buttonsize": {
//        "buckets": [ "small", "medium", "large" ],
//        "weight": "7:3:2"
//    }
//}
use fastly::http::header::{CACHE_CONTROL, COOKIE, SET_COOKIE};
use fastly::{Dictionary, Error, Request, Response};
use rand::distributions::WeightedIndex;
use rand::prelude::*;
use rand::rngs::StdRng;
use serde::{de, Deserialize, Deserializer};
use std::collections::HashMap;
use uuid::Uuid;

const BACKEND_NAME: &str = "origin_0";
const DICT_NAME: &str = "ab_config";
const COOKIE_NAME: &str = "ab_cid";

#[derive(Debug, Deserialize)]
struct ABTest {
    buckets: Vec<String>,
    #[serde(deserialize_with = "weight_deserializer")]
    weight: Vec<i32>,
}

// Custom deserializer to parse a weighting ratio expression like "7:3:2" into Vec<i32>.
fn weight_deserializer<'de, D>(deserializer: D) -> Result<Vec<i32>, D::Error>
where
    D: Deserializer<'de>,
{
    let weight_string = <&'de str>::deserialize(deserializer)?;
    weight_string
        .split(':')
        .map(str::parse)
        .collect::<Result<Vec<_>, _>>()
        .map_err(|e| {
            de::Error::custom(format!(
                "str::parse::<i32> returned an error while parsing {:?}: {}",
                weight_string, e
            ))
        })
}

struct ClientID {
    id: String,
    is_new: bool,
}

impl ClientID {
    fn new() -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            is_new: true,
        }
    }
    fn from_id(id: String) -> Self {
        Self { id, is_new: false }
    }
    fn as_setcookie(&self) -> String {
        format!(
            "{}={}; max-age=31536000; domain=example.com; path=/; secure; httponly",
            COOKIE_NAME, self.id
        )
    }
}

fn load_cookie(cookie: &str) -> HashMap<&str, &str> {
    cookie
        .split(';')
        .filter_map(|kv| kv.trim().split_once('='))
        .collect()
}

fn stringify_cookie(cookie_jar: HashMap<&str, &str>) -> String {
    cookie_jar
        .iter()
        .map(|(k, v)| format!("{}={}", k, v))
        .collect::<Vec<_>>()
        .join("; ")
}

fn create_rng(cid: &str, test_name: &str) -> StdRng {
    // Generate a random number generator based on a client ID and a test name as seed.
    let digest1: [u8; 16] = md5::compute(cid).into();
    let digest2: [u8; 16] = md5::compute(test_name).into();

    let mut seed: [u8; 32] = Default::default();
    seed[..16].copy_from_slice(&digest1);
    seed[16..].copy_from_slice(&digest2);

    rand::SeedableRng::from_seed(seed)
}

#[fastly::main]
fn main(mut req: Request) -> Result<Response, Error> {
    let abtest_config = Dictionary::open(DICT_NAME);
    if let Some(t) = abtest_config.get("tests") {
        let tests: Vec<String> = t.split(',').map(|t| t.trim().to_string()).collect();

        // Find a client ID in the Cookie header and remove it from the origin request
        // so that the origin will not generate different content based on the ID.
        // Allocate a client ID if they don't already have one.
        let cid = match req.get_header(COOKIE).cloned() {
            Some(cookie) => {
                let mut cookie_jar = load_cookie(cookie.to_str()?);
                match cookie_jar.remove(COOKIE_NAME) {
                    Some(id) => {
                        req.set_header("cookie", stringify_cookie(cookie_jar));
                        ClientID::from_id(id.to_string())
                    }
                    None => ClientID::new(),
                }
            }
            None => ClientID::new(),
        };

        // Assign the client to a bucket for each test and add the Fastly-ABTest-X header to the origin request.
        for test_name in tests.iter() {
            match abtest_config.get(test_name) {
                Some(v) => {
                    let abtest = serde_json::from_str::<ABTest>(&v).unwrap();
                    let mut rng = create_rng(&cid.id, test_name);

                    // Pick a bucket according to the weight.
                    let dist = WeightedIndex::new(&abtest.weight).unwrap();
                    let bucket = &abtest.buckets[dist.sample(&mut rng)];

                    println!("test={}, bucket={}", test_name, bucket);
                    req.set_header(format!("Fastly-ABTest-{}", test_name), bucket);
                }
                None => {
                    eprintln!(
                        "{} is not found in the dictionary. Sending the request as-is.",
                        test_name
                    );
                    return Ok(req.send(BACKEND_NAME)?);
                }
            }
        }
        let mut beresp = req.send(BACKEND_NAME)?;

        // If the client ID is not present in the original request, send them one
        match cid.is_new {
            true => {
                println!("CID not found assigning: {}", cid.id);
                beresp.set_header(SET_COOKIE, cid.as_setcookie());
                beresp.set_header(CACHE_CONTROL, "no-store");
            }
            false => println!("CID found in the Cookie: {}", cid.id),
        }

        return Ok(beresp);
    }

    Ok(req.send(BACKEND_NAME)?)
}