use crate::data::{Id, Version};
use crate::interpret::{Interpret, InterpretError, InterpretName, InterpretStatus, Outcome};
use crate::inventory::Inventory;
use crate::score::Score;
use crate::topology::{HelmCommand, Topology};
use async_trait::async_trait;
use helm_wrapper_rs;
use helm_wrapper_rs::blocking::{DefaultHelmExecutor, HelmExecutor};
use log::{debug, info, warn};
pub use non_blank_string_rs::NonBlankString;
use serde::Serialize;
use std::collections::HashMap;
use std::path::Path;
use std::process::{Command, Output, Stdio};
use std::str::FromStr;
use temp_file::TempFile;
use url::Url;

#[derive(Debug, Clone, Serialize)]
pub struct HelmRepository {
    name: String,
    url: Url,
    force_update: bool,
}
impl HelmRepository {
    pub fn new(name: String, url: Url, force_update: bool) -> Self {
        Self {
            name,
            url,
            force_update,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct HelmChartScore {
    pub namespace: Option<NonBlankString>,
    pub release_name: NonBlankString,
    pub chart_name: NonBlankString,
    pub chart_version: Option<NonBlankString>,
    pub values_overrides: Option<HashMap<NonBlankString, String>>,
    pub values_yaml: Option<String>,
    pub create_namespace: bool,

    /// Wether to run `helm upgrade --install` under the hood or only install when not present
    pub install_only: bool,
    pub repository: Option<HelmRepository>,
}

impl<T: Topology + HelmCommand> Score<T> for HelmChartScore {
    fn create_interpret(&self) -> Box<dyn Interpret<T>> {
        Box::new(HelmChartInterpret {
            score: self.clone(),
        })
    }

    fn name(&self) -> String {
        format!("{} {} HelmChartScore", self.release_name, self.chart_name)
    }
}

#[derive(Debug, Serialize)]
pub struct HelmChartInterpret {
    pub score: HelmChartScore,
}
impl HelmChartInterpret {
    fn add_repo(&self) -> Result<(), InterpretError> {
        let repo = match &self.score.repository {
            Some(repo) => repo,
            None => {
                info!("No Helm repository specified in the score. Skipping repository setup.");
                return Ok(());
            }
        };
        info!(
            "Ensuring Helm repository exists: Name='{}', URL='{}', ForceUpdate={}",
            repo.name, repo.url, repo.force_update
        );

        let mut add_args = vec!["repo", "add", &repo.name, repo.url.as_str()];
        if repo.force_update {
            add_args.push("--force-update");
        }

        let add_output = run_helm_command(&add_args)?;
        let full_output = format!(
            "{}\n{}",
            String::from_utf8_lossy(&add_output.stdout),
            String::from_utf8_lossy(&add_output.stderr)
        );

        match add_output.status.success() {
            true => {
                return Ok(());
            }
            false => {
                return Err(InterpretError::new(format!(
                    "Failed to add helm repository!\n{full_output}"
                )));
            }
        }
    }
}

fn run_helm_command(args: &[&str]) -> Result<Output, InterpretError> {
    let command_str = format!("helm {}", args.join(" "));
    debug!(
        "Got KUBECONFIG: `{}`",
        std::env::var("KUBECONFIG").unwrap_or("".to_string())
    );
    debug!("Running Helm command: `{}`", command_str);

    let output = Command::new("helm")
        .args(args)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .map_err(|e| {
            InterpretError::new(format!(
                "Failed to execute helm command '{}': {}. Is helm installed and in PATH?",
                command_str, e
            ))
        })?;

    if !output.status.success() {
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        warn!(
            "Helm command `{}` failed with status: {}\nStdout:\n{}\nStderr:\n{}",
            command_str, output.status, stdout, stderr
        );
    } else {
        debug!(
            "Helm command `{}` finished successfully. Status: {}",
            command_str, output.status
        );
    }

    Ok(output)
}

#[async_trait]
impl<T: Topology + HelmCommand> Interpret<T> for HelmChartInterpret {
    async fn execute(
        &self,
        _inventory: &Inventory,
        _topology: &T,
    ) -> Result<Outcome, InterpretError> {
        let ns = self
            .score
            .namespace
            .as_ref()
            .unwrap_or_else(|| todo!("Get namespace from active kubernetes cluster"));

        let tf: TempFile;
        let yaml_path: Option<&Path> = match self.score.values_yaml.as_ref() {
            Some(yaml_str) => {
                tf = temp_file::with_contents(yaml_str.as_bytes());
                Some(tf.path())
            }
            None => None,
        };

        self.add_repo()?;

        let helm_executor = DefaultHelmExecutor::new_with_opts(
            &NonBlankString::from_str("helm").unwrap(),
            None,
            900,
            false,
            false,
        );

        let mut helm_options = Vec::new();
        if self.score.create_namespace {
            helm_options.push(NonBlankString::from_str("--create-namespace").unwrap());
        }

        if self.score.install_only {
            let chart_list = match helm_executor.list(Some(ns)) {
                Ok(charts) => charts,
                Err(e) => {
                    return Err(InterpretError::new(format!(
                        "Failed to list scores in namespace {:?} because of error : {}",
                        self.score.namespace, e
                    )));
                }
            };

            if chart_list
                .iter()
                .any(|item| item.name == self.score.release_name.to_string())
            {
                info!(
                    "Release '{}' already exists in namespace '{}'. Skipping installation as install_only is true.",
                    self.score.release_name, ns
                );

                return Ok(Outcome::new(
                    InterpretStatus::SUCCESS,
                    format!(
                        "Helm Chart '{}' already installed to namespace {ns} and install_only=true",
                        self.score.release_name
                    ),
                ));
            } else {
                info!(
                    "Release '{}' not found in namespace '{}'. Proceeding with installation.",
                    self.score.release_name, ns
                );
            }
        }

        let res = helm_executor.install_or_upgrade(
            &ns,
            &self.score.release_name,
            &self.score.chart_name,
            self.score.chart_version.as_ref(),
            self.score.values_overrides.as_ref(),
            yaml_path,
            Some(&helm_options),
        );

        let status = match res {
            Ok(status) => status,
            Err(err) => return Err(InterpretError::new(err.to_string())),
        };

        match status {
            helm_wrapper_rs::HelmDeployStatus::Deployed => Ok(Outcome::new(
                InterpretStatus::SUCCESS,
                "Helm Chart deployed".to_string(),
            )),
            helm_wrapper_rs::HelmDeployStatus::PendingInstall => Ok(Outcome::new(
                InterpretStatus::RUNNING,
                "Helm Chart Pending install".to_string(),
            )),
            helm_wrapper_rs::HelmDeployStatus::PendingUpgrade => Ok(Outcome::new(
                InterpretStatus::RUNNING,
                "Helm Chart pending upgrade".to_string(),
            )),
            helm_wrapper_rs::HelmDeployStatus::Failed => Err(InterpretError::new(
                "Failed to install helm chart".to_string(),
            )),
        }
    }
    fn get_name(&self) -> InterpretName {
        todo!()
    }
    fn get_version(&self) -> Version {
        todo!()
    }
    fn get_status(&self) -> InterpretStatus {
        todo!()
    }
    fn get_children(&self) -> Vec<Id> {
        todo!()
    }
}
