/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/

use anyhow::{Result, anyhow};
use jellyremuxer::demuxers::{Demuxer, DemuxerNew, matroska::MatroskaDemuxer};
use std::{collections::BTreeMap, env::args, fs::File};

fn main() -> Result<()> {
    env_logger::init_from_env("LOG");
    let path = args().nth(1).ok_or(anyhow!("first arg is input path"))?;
    let file = File::open(path)?;
    let mut reader = MatroskaDemuxer::new(Box::new(file));

    let info = reader.info()?;

    reader.seek_cluster(None)?;
    let mut num_clusters = 0;
    let mut num_blocks = BTreeMap::<u64, usize>::new();
    let mut last_ts = 0;
    let mut total_size = 0;
    while let Some((_, cluster)) = reader.read_cluster()? {
        last_ts = cluster.timestamp * info.timestamp_scale;
        num_clusters += 1;
        for block in &cluster.simple_blocks {
            total_size += block.data.len() as u64;
            *num_blocks.entry(block.track).or_default() += 1;
        }
    }

    let average_duration = (last_ts / num_clusters) as f64 / 1_000_000_000.;
    let average_size = (total_size / num_clusters) as f64 / 1_000_000.;
    println!("{average_duration:>6.02}s {average_size:>6.02}MB");
    println!("{num_blocks:?}");

    Ok(())
}
