//! Merge job status queries.
use super::super::super::AgentPool;
use super::time::decode_server_start_time;

impl AgentPool {
    /// Check the status of a background merge job.
    ///
    /// Reads from the CRDT `merge_jobs` collection and reconstructs the full
    /// [`MergeJob`] struct. The CRDT `error` field encodes the `pid` for
    /// Running jobs (as `{"pid":N}`) and the serialised [`MergeReport`] for
    /// Completed jobs.
    pub fn get_merge_status(&self, story_id: &str) -> Option<crate::agents::merge::MergeJob> {
        let view = crate::crdt_state::read_merge_job(story_id)?;
        let (status, server_start_time) = match view.status.as_str() {
            "running" => {
                let t = decode_server_start_time(view.error.as_deref()).unwrap_or(0.0);
                (crate::agents::merge::MergeJobStatus::Running, t)
            }
            "completed" => {
                let report = view
                    .error
                    .as_deref()
                    .and_then(|e| serde_json::from_str::<crate::agents::merge::MergeReport>(e).ok())
                    .unwrap_or_else(|| crate::agents::merge::MergeReport {
                        story_id: story_id.to_string(),
                        result: crate::agents::merge::MergeResult::Other {
                            output: String::new(),
                            conflict_details: None,
                        },
                        worktree_cleaned_up: false,
                        story_archived: false,
                        report_path: None,
                    });
                (crate::agents::merge::MergeJobStatus::Completed(report), 0.0)
            }
            _ => {
                let err = view.error.unwrap_or_else(|| "Unknown error".to_string());
                (crate::agents::merge::MergeJobStatus::Failed(err), 0.0)
            }
        };
        Some(crate::agents::merge::MergeJob {
            story_id: story_id.to_string(),
            status,
            server_start_time,
            started_at: view.started_at,
        })
    }
}
