//! Helpers for pipeline-advance: spawning, QA-mode resolution, review-hold writing,
//! block-decision logic.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use tokio::sync::broadcast;

use super::super::super::super::CompletionReport;
use super::super::super::{AgentPool, StoryAgent};
use crate::io::watcher::WatcherEvent;
use crate::{slog, slog_error, slog_warn};
use std::path::Path;

/// type cycle between `start_agent` and `run_server_owned_completion`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn spawn_pipeline_advance(
    agents: Arc<tokio::sync::Mutex<HashMap<String, StoryAgent>>>,
    port: u16,
    story_id: &str,
    agent_name: &str,
    completion: CompletionReport,
    project_root: Option<PathBuf>,
    worktree_path: Option<PathBuf>,
    watcher_tx: broadcast::Sender<WatcherEvent>,
    merge_failure_reported: bool,
    previous_session_id: Option<String>,
) {
    let sid = story_id.to_string();
    let aname = agent_name.to_string();
    tokio::spawn(async move {
        let pool = AgentPool {
            agents,
            port,
            watcher_tx,
            status_broadcaster: Arc::new(crate::service::status::StatusBroadcaster::new()),
        };
        pool.run_pipeline_advance(
            &sid,
            &aname,
            completion,
            project_root,
            worktree_path,
            merge_failure_reported,
            previous_session_id,
        )
        .await;
    });
}

/// Resolve QA mode for a story.
///
/// Story 929: reads the typed `qa_mode` register; the legacy YAML fallback
/// is gone (the CRDT register is the only source).
pub(super) fn resolve_qa_mode_from_store(
    _project_root: &Path,
    story_id: &str,
    default: crate::io::story_metadata::QaMode,
) -> crate::io::story_metadata::QaMode {
    crate::crdt_state::read_item(story_id)
        .and_then(|view| view.qa_mode())
        .unwrap_or(default)
}

/// Mark a story as held for human review (story 945: `Stage::ReviewHold`).
///
/// The caller has just moved the story to QA via `move_story_to_qa`, so the
/// story is in `Stage::Qa`.  We transition to `Stage::ReviewHold { resume_to:
/// Qa, reason }` so the auto-assigner skips it while preserving the resume
/// target.
pub(super) fn write_review_hold_to_store(story_id: &str) {
    if let Err(e) = crate::pipeline_state::apply_transition_str(
        story_id,
        crate::pipeline_state::PipelineEvent::ReviewHold {
            reason: "Held for human review".to_string(),
        },
        None,
    ) {
        slog_error!("[pipeline] Cannot set review_hold for '{story_id}': {e}");
    }
}

/// Increment retry_count and block the story if it exceeds `max_retries`.
///
/// Returns `Some(reason)` if the story is now blocked (caller should NOT restart the agent).
/// Returns `None` if the story may be retried.
/// When `max_retries` is 0, retry limits are disabled.
pub(crate) fn should_block_story(
    story_id: &str,
    max_retries: u32,
    stage_label: &str,
) -> Option<String> {
    if max_retries == 0 {
        return None;
    }

    let new_count = crate::crdt_state::bump_retry_count(story_id) as u32;
    if new_count == 0 {
        slog_error!(
            "[pipeline] Failed to bump retry_count for '{story_id}': item not found in CRDT"
        );
        return None;
    }

    if new_count >= max_retries {
        let reason =
            format!("Retry limit exceeded ({new_count}/{max_retries}) at {stage_label} stage");
        slog_warn!(
            "[pipeline] Story '{story_id}' reached retry limit ({new_count}/{max_retries}) \
             at {stage_label} stage. Marking as blocked."
        );
        if let Err(e) = crate::agents::lifecycle::transition_to_blocked(story_id, &reason) {
            slog_error!("[pipeline] Failed to transition '{story_id}' to Blocked: {e}");
        }
        Some(reason)
    } else {
        slog!(
            "[pipeline] Story '{story_id}' retry {new_count}/{max_retries} at {stage_label} stage."
        );
        None
    }
}
