/*
    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::plugins::{ImportContext, ImportPlugin, PluginInfo};
use anyhow::Result;
use jellycommon::{IdentifierType, NodeID, NodeKind};
use jellyremuxer::matroska::Segment;
use std::{collections::HashMap, path::Path};

pub struct Tags;
impl ImportPlugin for Tags {
    fn info(&self) -> PluginInfo {
        PluginInfo {
            name: "tags",
            handle_media: true,
            ..Default::default()
        }
    }
    fn media(&self, ct: &ImportContext, node: NodeID, _path: &Path, seg: &Segment) -> Result<()> {
        let tags = seg
            .tags
            .first()
            .map(|tags| {
                tags.tags
                    .iter()
                    .flat_map(|t| t.simple_tags.clone())
                    .map(|st| (st.name, st.string.unwrap_or_default()))
                    .collect::<HashMap<_, _>>()
            })
            .unwrap_or_default();

        ct.db.update_node_init(node, |node| {
            node.title = seg.info.title.clone();
            for (key, value) in tags {
                match key.as_str() {
                    "DESCRIPTION" => node.description = Some(value),
                    "SYNOPSIS" => node.description = Some(value),
                    "COMMENT" => node.tagline = Some(value),
                    "CONTENT_TYPE" => {
                        node.kind = match value.to_lowercase().trim() {
                            "movie" | "documentary" | "film" => NodeKind::Movie,
                            "music" | "recording" => NodeKind::Music,
                            _ => continue,
                        }
                    }
                    _ => node.identifiers.extend(Some(match key.as_str() {
                        "MUSICBRAINZ_TRACKID" => (IdentifierType::MusicbrainzRecording, value),
                        "MUSICBRAINZ_ARTISTID" => (IdentifierType::MusicbrainzArtist, value),
                        "MUSICBRAINZ_ALBUMID" => (IdentifierType::MusicbrainzRelease, value),
                        "MUSICBRAINZ_ALBUMARTISTID" => continue,
                        "MUSICBRAINZ_RELEASEGROUPID" => {
                            (IdentifierType::MusicbrainzReleaseGroup, value)
                        }
                        "ISRC" => (IdentifierType::Isrc, value),
                        "BARCODE" => (IdentifierType::Barcode, value),
                        _ => continue,
                    })),
                }
            }
        })?;
        Ok(())
    }
}
