/*
    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::{Context, Result, anyhow};
use jellycache::init_cache;
use jellylogic::init_database;
use serde::Deserialize;
use std::env::{args, var};
use tokio::fs::read_to_string;

#[derive(Debug, Deserialize)]
struct Config {
    transcoder: jellytranscoder::Config,
    ui: jellyui::Config,
    stream: jellystream::Config,
    cache: jellycache::Config,
    server: crate::Config,
    logic: jellylogic::Config,
    import: jellyimport::Config,
}

pub async fn load_config() -> Result<()> {
    let path = args()
        .nth(1)
        .or_else(|| var("JELLYTHING_CONFIG").ok())
        .ok_or(anyhow!(
            "No config supplied. Use first argument or JELLYTHING_CONFIG environment variable."
        ))?;

    let config_raw = read_to_string(path).await.context("reading main config")?;
    let config: Config = serde_yaml_ng::from_str(&config_raw).context("parsing main config")?;

    *jellystream::CONF_PRELOAD.lock().unwrap() = Some(config.stream);
    *jellytranscoder::CONF_PRELOAD.lock().unwrap() = Some(config.transcoder);
    *jellycache::CONF_PRELOAD.lock().unwrap() = Some(config.cache);
    *jellylogic::CONF_PRELOAD.lock().unwrap() = Some(config.logic);
    *jellyimport::CONF_PRELOAD.lock().unwrap() = Some(config.import);
    *crate::CONF_PRELOAD.lock().unwrap() = Some(config.server);
    *jellyui::CONF_PRELOAD.lock().unwrap() = Some(config.ui);

    init_cache()?;
    init_database()?;

    Ok(())
}
