use std::collections::BTreeMap;

use kube::CustomResource;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::modules::monitoring::alert_rule::prometheus_alert_rule::PrometheusAlertRule;

use super::crd_default_rules::build_default_application_rules;

#[derive(CustomResource, Debug, Serialize, Deserialize, Clone, JsonSchema)]
#[kube(
    group = "monitoring.coreos.com",
    version = "v1",
    kind = "PrometheusRule",
    plural = "prometheusrules",
    namespaced
)]
#[serde(rename_all = "camelCase")]
pub struct PrometheusRuleSpec {
    pub groups: Vec<RuleGroup>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RuleGroup {
    pub name: String,
    pub rules: Vec<Rule>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct Rule {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alert: Option<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expr: Option<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub for_: Option<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub labels: Option<std::collections::BTreeMap<String, String>>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub annotations: Option<std::collections::BTreeMap<String, String>>,
}

impl From<PrometheusAlertRule> for Rule {
    fn from(value: PrometheusAlertRule) -> Self {
        Rule {
            alert: Some(value.alert),
            expr: Some(value.expr),
            for_: value.r#for,
            labels: Some(value.labels.into_iter().collect::<BTreeMap<_, _>>()),
            annotations: Some(value.annotations.into_iter().collect::<BTreeMap<_, _>>()),
        }
    }
}
