use crate::config::AppConfig;
use common_contracts::workflow_harness::TaskState;
use common_contracts::observability::{TaskProgress, ObservabilityTaskStatus};
use dashmap::DashMap;
use uuid::Uuid;
use std::sync::Arc;
use chrono::Utc;

#[derive(Clone)]
pub struct AppState {
    pub config: Arc<AppConfig>,
    pub tasks: Arc<DashMap<Uuid, TaskProgress>>,
}

impl AppState {
    pub fn new(config: AppConfig) -> Self {
        Self {
            config: Arc::new(config),
            tasks: Arc::new(DashMap::new()),
        }
    }
}

#[async_trait::async_trait]
impl TaskState for AppState {
    fn update_status(&self, task_id: Uuid, status: ObservabilityTaskStatus, progress: u8, details: String) {
        self.tasks.entry(task_id)
            .and_modify(|t| {
                t.status = status;
                t.progress_percent = progress;
                t.details = details.clone();
            })
            .or_insert_with(|| TaskProgress {
                request_id: task_id,
                task_name: "mock_task".to_string(),
                status,
                progress_percent: progress,
                details,
                started_at: Utc::now(),
            });
    }

    fn fail_task(&self, task_id: Uuid, error: String) {
        self.update_status(task_id, ObservabilityTaskStatus::Failed, 0, error);
    }

    fn complete_task(&self, task_id: Uuid, details: String) {
        self.update_status(task_id, ObservabilityTaskStatus::Completed, 100, details);
    }

    fn get_nats_addr(&self) -> String {
        self.config.nats_addr.clone()
    }

    fn get_persistence_url(&self) -> String {
        // Mock provider doesn't use persistence client in this simplified version,
        // but if we need it, we can add it to config.
        // For now return dummy or config value.
        "http://data-persistence-service:3000/api/v1".to_string()
    }
}
