/*
    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 crate::{DATABASE, session::Session};
use anyhow::{Result, anyhow};
use jellycommon::{Asset, NodeID, SourceTrackKind, TrackSource};

pub async fn get_node_thumbnail(_session: &Session, id: NodeID, t: f64) -> Result<Asset> {
    let node = DATABASE
        .get_node(id)?
        .ok_or(anyhow!("node does not exist"))?;

    let media = node.media.as_ref().ok_or(anyhow!("no media"))?;
    let (thumb_track_index, _thumb_track) = media
        .tracks
        .iter()
        .enumerate()
        .find(|(_i, t)| matches!(t.kind, SourceTrackKind::Video { .. }))
        .ok_or(anyhow!("no video track to create a thumbnail of"))?;
    let source = media
        .tracks
        .get(thumb_track_index)
        .ok_or(anyhow!("no source"))?;
    let thumb_track_source = source.source.clone();

    if t < 0. || t > media.duration {
        Err(anyhow!("thumbnail instant not within media duration"))?
    }

    let step = 8.;
    let t = (t / step).floor() * step;

    Ok(match thumb_track_source {
        TrackSource::Local(path, _) => {
            Asset(jellytranscoder::thumbnail::create_thumbnail(&path, t)?)
        }
        TrackSource::Remote(_) => {
            // // TODO in the new system this is preferrably a property of node ext for regular fed
            // let session = fed
            //     .get_session(
            //         thumb_track
            //             .federated
            //             .last()
            //             .ok_or(anyhow!("federation broken"))?,
            //     )
            //     .await?;

            // async_cache_file("fed-thumb", (id.0, t as i64), |out| {
            //     session.node_thumbnail(out, id.0.into(), 2048, t)
            // })
            // .await?
            todo!()
        }
    })
}
