/*
    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::{anyhow, Result};
use jellycache::{cache_memory, HashKey};
use jellyremuxer::{demuxers::create_demuxer_autodetect, matroska::Segment};
use std::{fs::File, path::Path, sync::Arc};

pub fn read_metadata(path: &Path) -> Result<Arc<Segment>> {
    cache_memory(
        &format!("media/stream-metadata/{}.json", HashKey(path)),
        move || {
            let media = File::open(path)?;
            let mut media = create_demuxer_autodetect(Box::new(media))?
                .ok_or(anyhow!("media format unknown"))?;

            let info = media.info()?;
            let tracks = media.tracks()?;
            Ok(Segment {
                info,
                tracks,
                ..Default::default()
            })
        },
    )
}
