use anyhow::Result;
use std::path::PathBuf;
use std::fs;
use tracing::info;

pub struct VectorDbSetup;

impl VectorDbSetup {
    pub async fn setup(conf_path: PathBuf, data_path: PathBuf) -> Result<()> {
        let config_dir = conf_path.join("vector_db");
        fs::create_dir_all(&config_dir)?;

        let data_dir = data_path.join("vector_db");
        fs::create_dir_all(&data_dir)?;

        let cert_dir = conf_path.join("system/certificates/vectordb");

        // Convert to absolute paths for Qdrant config
        let data_dir_abs = fs::canonicalize(&data_dir).unwrap_or(data_dir);
        let cert_dir_abs = fs::canonicalize(&cert_dir).unwrap_or(cert_dir);

        let config_content = generate_qdrant_config(&data_dir_abs, &cert_dir_abs);

        let config_path = config_dir.join("config.yaml");
        fs::write(&config_path, config_content)?;

        info!("Qdrant vector_db configuration written to {:?}", config_path);

        Ok(())
    }
}

pub fn generate_qdrant_config(data_dir: &PathBuf, cert_dir: &PathBuf) -> String {
    let data_path = data_dir.to_string_lossy();
    let cert_path = cert_dir.join("server.crt").to_string_lossy().to_string();
    let key_path = cert_dir.join("server.key").to_string_lossy().to_string();
    let ca_path = cert_dir.join("ca.crt").to_string_lossy().to_string();

    format!(
        r#"# Qdrant configuration with TLS enabled
# Generated by BotServer bootstrap

log_level: INFO

storage:
  storage_path: {data_path}
  snapshots_path: {data_path}/snapshots
  on_disk_payload: true

service:
  host: 0.0.0.0
  http_port: 6333
  grpc_port: 6334
  enable_tls: true

tls:
  cert: {cert_path}
  key: {key_path}
  ca_cert: {ca_path}
  verify_https_client_certificate: false

cluster:
  enabled: false

telemetry_disabled: true
"#
    )
}

pub async fn generate_vector_db_config(config_path: PathBuf, data_path: PathBuf) -> Result<()> {
    VectorDbSetup::setup(config_path, data_path).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn test_generate_qdrant_config() {
        let data_dir = PathBuf::from("/tmp/qdrant/data");
        let cert_dir = PathBuf::from("/tmp/qdrant/certs");

        let config = generate_qdrant_config(&data_dir, &cert_dir);

        assert!(config.contains("enable_tls: true"));
        assert!(config.contains("http_port: 6333"));
        assert!(config.contains("grpc_port: 6334"));
        assert!(config.contains("/tmp/qdrant/data"));
        assert!(config.contains("/tmp/qdrant/certs/server.crt"));
        assert!(config.contains("/tmp/qdrant/certs/server.key"));
    }
}
