/*
    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::{env::args, fs::File};
use winter_matroska::TrackType;

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 tracks = reader.tracks()?.unwrap();
    let video_track = tracks
        .entries
        .iter()
        .find(|t| matches!(t.track_type, TrackType::Video))
        .map(|t| t.track_number)
        .unwrap();

    reader.seek_cluster(None)?;
    let mut num_kf_first = 0;
    let mut num_kf_later = 0;
    while let Some((_, cluster)) = reader.read_cluster()? {
        let mut first = true;
        for block in cluster.simple_blocks {
            if block.track != video_track {
                continue;
            }
            if block.flags.keyframe() {
                if first {
                    num_kf_first += 1
                } else {
                    num_kf_later += 1;
                }
            }
            first = false
        }
    }

    println!("{num_kf_first:>4} kf first");
    println!("{num_kf_later:>4} kf later");
    Ok(())
}
