use std::env;
use anyhow::{Result, Context};
use serde::Deserialize;

#[derive(Clone, Deserialize, Debug)]
pub struct AppConfig {
    pub nats_addr: String,
    pub server_port: u16,
    pub data_persistence_service_url: String,
    pub workflow_data_path: String,
}

impl AppConfig {
    pub fn load() -> Result<Self> {
        let nats_addr = env::var("NATS_ADDR").unwrap_or_else(|_| "nats://nats:4222".to_string());
        let server_port = env::var("SERVER_PORT")
            .unwrap_or_else(|_| "8005".to_string())
            .parse()
            .context("SERVER_PORT must be a number")?;
        // Note: The previous default value included "/api/v1", but PersistenceClient might expect the base URL.
        // However, looking at PersistenceClient implementation:
        // let url = format!("{}/history", self.base_url);
        // And in data-persistence-service api/mod.rs:
        // .route("/api/v1/templates", ...)
        // So the client should point to the root, OR the routes should not have /api/v1 prefix if client has it.
        
        // Let's check data-persistence-service again.
        // It routes:
        // .route("/api/v1/templates", ...)
        
        // If PersistenceClient base_url is "http://svc:3000/api/v1", then
        // format!("{}/api/v1/templates", base_url) -> "http://svc:3000/api/v1/api/v1/templates" (DOUBLE!)
        
        // Correct fix: The base URL should NOT include /api/v1 if the client methods append it, OR the client methods should not append it.
        // Checking common-contracts/persistence_client.rs:
        // pub async fn get_templates(&self) -> Result<Vec<AnalysisTemplateSummary>> {
        //    let url = format!("{}/api/v1/templates", self.base_url);
        // }
        
        // So base_url MUST NOT end with /api/v1.
        
        let data_persistence_service_url = env::var("DATA_PERSISTENCE_SERVICE_URL")
            .unwrap_or_else(|_| "http://data-persistence-service:3000".to_string());
            
        let workflow_data_path = env::var("WORKFLOW_DATA_PATH")
            .unwrap_or_else(|_| "/mnt/workflow_data".to_string());

        Ok(Self {
            nats_addr,
            server_port,
            data_persistence_service_url,
            workflow_data_path,
        })
    }
}
