use std::{
    fs::File,
    io::{self, BufWriter, Write},
};

use az::Az;
use bytemuck::cast_slice;

fn main() -> Result<(), io::Error> {
    let mut chain = BufWriter::new(File::create("assets/chain")?);

    let mut indices = vec![0u32; (i32::MAX - 1).az::<usize>()];

    let mut x = 1;
    let mut count = 0;

    loop {
        if count % 1_000_000 == 0 {
            println!("current: {count:0>10}");
        }
        let next = seedrand(x);

        indices[x.az::<usize>() - 1] = count;
        chain.write_all(&next.to_ne_bytes())?;

        x = next;
        count += 1;
        if x == 1 {
            break;
        }
    }

    File::create("assets/table")?.write_all(cast_slice(&indices))?;

    Ok(())
}

const fn seedrand(x: i32) -> i32 {
    const A: i32 = 48_271;
    const Q: i32 = 44_488;
    const R: i32 = 3_399;

    let hi = x / Q;
    let lo = x % Q;
    let x = A * lo - R * hi;
    if x < 0 { x + i32::MAX } else { x }
}
