use std::{
    env::{self, VarError},
    fs, io,
    path::PathBuf,
};

use rudof_iri::IriS;
use rudof_rdf::rdf_core::vocabs::RdfsVocab;
use serde::{Deserialize, Serialize};
use shex_validation::ShExConfig;
use thiserror::Error;

use crate::shex_to_uml::{Direction, LineType};

pub const DEFAULT_REPLACE_IRI_BY_LABEL: bool = true;

#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct ShEx2UmlConfig {
    pub plantuml_path: Option<PathBuf>,

    /// A list of IRIs to use as annotation labels in the generated PlantUML diagram. If empty, the default is `rdfs:label`.
    pub annotation_label: Vec<IriS>,

    /// Whether to replace IRIs by their labels in the generated PlantUML diagram. If `None`, the default is `true`.
    pub replace_iri_by_label: Option<bool>,

    /// Whether to use shadowing in the generated PlantUML diagram. If `None`, the default is `true`.
    pub shadowing: Option<bool>,

    /// The line type to use in the generated PlantUML diagram. If `None`, the default is `LineType::Polyline`.
    pub line_type: Option<LineType>,

    /// The direction of the generated PlantUML diagram. If `None`, the default is `Direction::TopToBottom`.
    pub direction: Option<Direction>,

    /// Configuration for ShEx. If `None`, the default configuration is used.
    pub shex: Option<ShExConfig>,
}

impl ShEx2UmlConfig {
    pub fn new() -> ShEx2UmlConfig {
        Self {
            annotation_label: vec![RdfsVocab::rdfs_label()],
            replace_iri_by_label: None,
            shex: Some(ShExConfig::default()),
            shadowing: Some(true),

            line_type: Some(LineType::default()),
            direction: Some(Direction::default()),
            plantuml_path: None,
        }
    }

    pub fn shex_config(&self) -> ShExConfig {
        match &self.shex {
            None => ShExConfig::default(),
            Some(sc) => sc.clone(),
        }
    }

    pub fn replace_iri_by_label(&self) -> bool {
        self.replace_iri_by_label.unwrap_or(DEFAULT_REPLACE_IRI_BY_LABEL)
    }

    pub fn from_file(file_name: &str) -> Result<ShEx2UmlConfig, ShEx2UmlConfigError> {
        let config_str = fs::read_to_string(file_name).map_err(|e| ShEx2UmlConfigError::ReadingConfig {
            path_name: file_name.to_string(),
            error: e,
        })?;
        toml::from_str::<ShEx2UmlConfig>(&config_str).map_err(|e| ShEx2UmlConfigError::Toml {
            path_name: file_name.to_string(),
            error: e,
        })
    }

    pub fn plantuml_path(&self) -> PathBuf {
        self.plantuml_path.clone().unwrap_or_else(|| {
            env::var("PLANTUML")
                .map(PathBuf::from)
                .unwrap_or_else(|_| env::current_dir().unwrap())
        })
    }
}

#[derive(Error, Debug)]
pub enum ShEx2UmlConfigError {
    #[error("Reading path {path_name:?} error: {error:?}")]
    ReadingConfig { path_name: String, error: io::Error },

    #[error("Reading TOML from {path_name:?}. Error: {error:?}")]
    Toml { path_name: String, error: toml::de::Error },

    #[error("Accessing environment variable {var_name}: {error}")]
    EnvVar { var_name: String, error: VarError },
}

impl Default for ShEx2UmlConfig {
    fn default() -> Self {
        Self::new()
    }
}
