use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// A provider configuration bound to a specific agent type.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "target", rename_all = "kebab-case")]
pub enum Provider {
    #[serde(rename = "claude-code")]
    ClaudeCode {
        name: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        model: Option<String>,
        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
        env: HashMap<String, String>,
    },
    #[serde(rename = "codex")]
    Codex {
        name: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        api_key: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        base_url: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        model: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        model_provider: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        review_model: Option<String>,
    },
}

impl Provider {
    pub fn name(&self) -> &str {
        match self {
            Provider::ClaudeCode { name, .. } => name,
            Provider::Codex { name, .. } => name,
        }
    }

    pub fn target(&self) -> &str {
        match self {
            Provider::ClaudeCode { .. } => "claude-code",
            Provider::Codex { .. } => "codex",
        }
    }

    /// Merge update fields into this provider. Only `Some(...)` fields are applied.
    pub fn update(
        &mut self,
        model: Option<&str>,
        key: Option<&str>,
        url: Option<&str>,
        model_provider: Option<&str>,
        review_model: Option<&str>,
        env: &[(String, String)],
    ) {
        match self {
            Provider::ClaudeCode {
                model: m,
                env: e,
                ..
            } => {
                if let Some(val) = model {
                    *m = Some(val.to_string());
                }
                for (k, v) in env {
                    e.insert(k.clone(), v.clone());
                }
            }
            Provider::Codex {
                api_key: ak,
                base_url: bu,
                model: m,
                model_provider: mp,
                review_model: rm,
                ..
            } => {
                if let Some(val) = key {
                    *ak = Some(val.to_string());
                }
                if let Some(val) = url {
                    *bu = Some(val.to_string());
                }
                if let Some(val) = model {
                    *m = Some(val.to_string());
                }
                if let Some(val) = model_provider {
                    *mp = Some(val.to_string());
                }
                if let Some(val) = review_model {
                    *rm = Some(val.to_string());
                }
            }
        }
    }
}

/// The root encrypted data structure.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ProviderStore {
    pub version: u32,
    pub providers: Vec<Provider>,
}

impl Default for ProviderStore {
    fn default() -> Self {
        Self {
            version: 1,
            providers: Vec::new(),
        }
    }
}
