use async_trait::async_trait;
use log::debug;
use serde::Serialize;
use std::collections::HashMap;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::process::{Command, Output};
use temp_dir::{self, TempDir};
use temp_file::TempFile;

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, K8sclient, Topology};

#[derive(Clone)]
pub struct HelmCommandExecutor {
    pub env: HashMap<String, String>,
    pub path: Option<PathBuf>,
    pub args: Vec<String>,
    pub api_versions: Option<Vec<String>>,
    pub kube_version: String,
    pub debug: Option<bool>,
    pub globals: HelmGlobals,
    pub chart: HelmChart,
}

#[derive(Clone)]
pub struct HelmGlobals {
    pub chart_home: Option<PathBuf>,
    pub config_home: Option<PathBuf>,
}

#[derive(Debug, Clone, Serialize)]
pub struct HelmChart {
    pub name: String,
    pub version: Option<String>,
    pub repo: Option<String>,
    pub release_name: Option<String>,
    pub namespace: Option<String>,
    pub additional_values_files: Vec<PathBuf>,
    pub values_file: Option<PathBuf>,
    pub values_inline: Option<String>,
    pub include_crds: Option<bool>,
    pub skip_hooks: Option<bool>,
    pub api_versions: Option<Vec<String>>,
    pub kube_version: Option<String>,
    pub name_template: String,
    pub skip_tests: Option<bool>,
    pub debug: Option<bool>,
}

impl HelmCommandExecutor {
    pub fn generate(mut self) -> Result<String, std::io::Error> {
        if self.globals.chart_home.is_none() {
            self.globals.chart_home = Some(PathBuf::from("charts"));
        }

        if self
            .clone()
            .chart
            .clone()
            .chart_exists_locally(self.clone().globals.chart_home.unwrap())
            .is_none()
        {
            if self.chart.repo.is_none() {
                return Err(std::io::Error::new(
                    ErrorKind::Other,
                    "Chart doesn't exist locally and no repo specified",
                ));
            }
            self.clone().run_command(
                self.chart
                    .clone()
                    .pull_command(self.globals.chart_home.clone().unwrap()),
            )?;
        }

        let out = match self.clone().run_command(
            self.chart
                .clone()
                .helm_args(self.globals.chart_home.clone().unwrap()),
        ) {
            Ok(out) => out,
            Err(e) => return Err(e),
        };

        // TODO: don't use unwrap here
        let s = String::from_utf8(out.stdout).unwrap();
        debug!("helm stderr: {}", String::from_utf8(out.stderr).unwrap());
        debug!("helm status: {}", out.status);
        debug!("helm output: {s}");

        let clean = s.split_once("---").unwrap().1;

        Ok(clean.to_string())
    }

    pub fn version(self) -> Result<String, std::io::Error> {
        let out = match self.run_command(vec![
            "version".to_string(),
            "-c".to_string(),
            "--short".to_string(),
        ]) {
            Ok(out) => out,
            Err(e) => return Err(e),
        };

        // TODO: don't use unwrap
        Ok(String::from_utf8(out.stdout).unwrap())
    }

    pub fn run_command(mut self, mut args: Vec<String>) -> Result<Output, std::io::Error> {
        if let Some(d) = self.debug {
            if d {
                args.push("--debug".to_string());
            }
        }

        let path = if let Some(p) = self.path {
            p
        } else {
            PathBuf::from("helm")
        };

        let config_home = match self.globals.config_home {
            Some(p) => p,
            None => PathBuf::from(TempDir::new()?.path()),
        };

        match self.chart.values_inline {
            Some(yaml_str) => {
                let tf: TempFile;
                tf = temp_file::with_contents(yaml_str.as_bytes());
                self.chart
                    .additional_values_files
                    .push(PathBuf::from(tf.path()));
            }
            None => (),
        };

        self.env.insert(
            "HELM_CONFIG_HOME".to_string(),
            config_home.to_str().unwrap().to_string(),
        );
        self.env.insert(
            "HELM_CACHE_HOME".to_string(),
            config_home.to_str().unwrap().to_string(),
        );
        self.env.insert(
            "HELM_DATA_HOME".to_string(),
            config_home.to_str().unwrap().to_string(),
        );

        Command::new(path).envs(self.env).args(args).output()
    }
}

impl HelmChart {
    pub fn chart_exists_locally(self, chart_home: PathBuf) -> Option<PathBuf> {
        let chart_path =
            PathBuf::from(chart_home.to_str().unwrap().to_string() + "/" + &self.name.to_string());

        if chart_path.exists() {
            Some(chart_path)
        } else {
            None
        }
    }

    pub fn pull_command(self, chart_home: PathBuf) -> Vec<String> {
        let mut args = vec![
            "pull".to_string(),
            "--untar".to_string(),
            "--untardir".to_string(),
            chart_home.to_str().unwrap().to_string(),
        ];

        match self.repo {
            Some(r) => {
                if r.starts_with("oci://") {
                    args.push(String::from(
                        r.trim_end_matches("/").to_string() + "/" + self.name.clone().as_str(),
                    ));
                } else {
                    args.push("--repo".to_string());
                    args.push(r.to_string());

                    args.push(self.name);
                }
            }
            None => args.push(self.name),
        };

        match self.version {
            Some(v) => {
                args.push("--version".to_string());
                args.push(v.to_string());
            }
            None => (),
        }

        args
    }

    pub fn helm_args(self, chart_home: PathBuf) -> Vec<String> {
        let mut args: Vec<String> = vec!["template".to_string()];

        match self.release_name {
            Some(rn) => args.push(rn.to_string()),
            None => args.push("--generate-name".to_string()),
        }

        args.push(
            PathBuf::from(chart_home.to_str().unwrap().to_string() + "/" + self.name.as_str())
                .to_str()
                .unwrap()
                .to_string(),
        );

        if let Some(n) = self.namespace {
            args.push("--namespace".to_string());
            args.push(n.to_string());
        }

        if let Some(f) = self.values_file {
            args.push("-f".to_string());
            args.push(f.to_str().unwrap().to_string());
        }

        for f in self.additional_values_files {
            args.push("-f".to_string());
            args.push(f.to_str().unwrap().to_string());
        }

        if let Some(vv) = self.api_versions {
            for v in vv {
                args.push("--api-versions".to_string());
                args.push(v);
            }
        }

        if let Some(kv) = self.kube_version {
            args.push("--kube-version".to_string());
            args.push(kv);
        }

        if let Some(crd) = self.include_crds {
            if crd {
                args.push("--include-crds".to_string());
            }
        }

        if let Some(st) = self.skip_tests {
            if st {
                args.push("--skip-tests".to_string());
            }
        }

        if let Some(sh) = self.skip_hooks {
            if sh {
                args.push("--no-hooks".to_string());
            }
        }

        if let Some(d) = self.debug {
            if d {
                args.push("--debug".to_string());
            }
        }

        args
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct HelmChartScoreV2 {
    pub chart: HelmChart,
}

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

    fn name(&self) -> String {
        format!(
            "{} {} HelmChartScoreV2",
            self.chart
                .release_name
                .clone()
                .unwrap_or("Unknown".to_string()),
            self.chart.name
        )
    }
}

#[derive(Debug, Serialize)]
pub struct HelmChartInterpretV2 {
    pub score: HelmChartScoreV2,
}
impl HelmChartInterpretV2 {}

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

        let helm_executor = HelmCommandExecutor {
            env: HashMap::new(),
            path: None,
            args: vec![],
            api_versions: None,
            kube_version: "v1.33.0".to_string(),
            debug: Some(false),
            globals: HelmGlobals {
                chart_home: None,
                config_home: None,
            },
            chart: self.score.chart.clone(),
        };

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

        let res = helm_executor.generate();

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

        // TODO: implement actually applying the YAML from the templating in the generate function to a k8s cluster, having trouble passing in straight YAML into the k8s client

        // let k8s_resource = k8s_openapi::serde_json::from_str(output.as_str()).unwrap();

        // let client = topology
        //     .k8s_client()
        //     .await
        //     .expect("Environment should provide enough information to instanciate a client")
        //     .apply_namespaced(&vec![output], Some(ns.to_string().as_str()));
        // match client.apply_yaml(output) {
        //     Ok(_) => return Ok(Outcome::success("Helm chart deployed".to_string())),
        //     Err(e) => return Err(InterpretError::new(e)),
        // }

        Ok(Outcome::success("Helm chart deployed".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!()
    }
}
