//! Periodic sweep of completed work items from `5_done` to `6_archived`.
//!
//! Items that have been in `5_done` for longer than the configured retention
//! period are automatically promoted to `6_archived` via CRDT state transitions.

use crate::slog;
use std::time::Duration;

/// Sweep items in `5_done` whose `merged_at` timestamp exceeds the retention
/// duration to `6_archived` via CRDT state transitions.
///
/// All state is read from and written to CRDT — no filesystem access.
/// Worktree pruning is handled separately by the CRDT event subscriber.
pub(crate) fn sweep_done_to_archived(done_retention: Duration) {
    use crate::pipeline_state::{PipelineEvent, Stage, read_all_typed, stage_dir_name, transition};

    for item in read_all_typed() {
        if let Stage::Done { merged_at, .. } = &item.stage {
            let age = chrono::Utc::now()
                .signed_duration_since(*merged_at)
                .to_std()
                .unwrap_or_default();
            if age >= done_retention {
                let story_id = item.story_id.0.clone();
                match transition(item.stage.clone(), PipelineEvent::Accepted) {
                    Ok(new_stage) => {
                        crate::crdt_state::write_item(
                            &story_id,
                            stage_dir_name(&new_stage),
                            None,
                            None,
                            None,
                            Some(false),
                            None,
                            None,
                            None,
                            None,
                        );
                        slog!("[watcher] sweep: promoted {story_id} → 6_archived/");
                    }
                    Err(e) => {
                        slog!("[watcher] sweep: transition error for {story_id}: {e}");
                    }
                }
            }
        }
    }
}
