//! Time-shard swarm harness (spec §3). Run as a subprocess by
//! `tests/timeshard.rs` under `AILANG_RC_STATS=1`.
//!
//! argv: `<data_dir> <symbol> <from:to> [<from:to> ...]` — one
//! inclusive Unix-ms window per shard. Date math lives in the test
//! (chrono); this bin is date-math-free. Spawns one thread per
//! window, each building its OWN `Kernel` (`Ctx: !Send` forces
//! one-ctx-per-thread — a shared-ctx design is `error[E0277]`).
//! Prints, in shard order, `RESULT <idx> <from> <to> <accbits:016x>
//! <n>`, then one `TIMING total_ticks=<Σn> elapsed_ms=<wall>` line
//! (the friction-harvest observation; the test prints it to stderr,
//! it is not asserted).

use std::sync::Arc;
use std::time::Instant;

use ail_embed::adapter::fold_window;
use data_server::DataServer;

fn main() {
    let mut args = std::env::args().skip(1);
    let data_dir = args.next().expect("argv[1] = data dir");
    let symbol = args.next().expect("argv[2] = symbol");
    let windows: Vec<(i64, i64)> = args
        .map(|a| {
            let (f, t) = a.split_once(':').expect("window arg is from:to");
            (
                f.parse::<i64>().expect("from_ms i64"),
                t.parse::<i64>().expect("to_ms i64"),
            )
        })
        .collect();
    assert!(
        windows.len() >= 2,
        "need >= 2 disjoint windows for a time-shard, got {}",
        windows.len()
    );

    let server = Arc::new(DataServer::new(&data_dir));

    let started = Instant::now();
    let handles: Vec<_> = windows
        .iter()
        .copied()
        .enumerate()
        .map(|(idx, (from, to))| {
            let srv = Arc::clone(&server);
            let sym = symbol.clone();
            // Each thread builds its own Kernel inside the closure —
            // Kernel/Ctx are !Send, so this is the ONLY shape that
            // compiles (one ctx per thread, type-enforced).
            std::thread::spawn(move || {
                let (acc, n) = fold_window(&srv, &sym, from, to)
                    .expect("window has a tick stream");
                (idx, from, to, acc, n)
            })
        })
        .collect();

    let mut results: Vec<(usize, i64, i64, f64, i64)> = handles
        .into_iter()
        .map(|h| h.join().expect("shard thread panicked"))
        .collect();
    let elapsed_ms = started.elapsed().as_millis();
    results.sort_by_key(|r| r.0);

    let mut total_ticks: i64 = 0;
    for (idx, from, to, acc, n) in &results {
        total_ticks += *n;
        println!("RESULT {idx} {from} {to} {:016x} {n}", acc.to_bits());
    }
    println!("TIMING total_ticks={total_ticks} elapsed_ms={elapsed_ms}");
}
