//! Discord incoming message dispatch and command handling.

use std::collections::HashSet;
use std::sync::Arc;

use crate::chat::ChatTransport;
use crate::chat::transport::matrix::{ConversationEntry, ConversationRole, RoomConversation};
use crate::chat::util::is_permission_approval;
use crate::http::context::PermissionDecision;
use crate::services::Services;
use crate::slog;

use super::format::markdown_to_discord;
use super::history::{DiscordConversationHistory, save_discord_history};
use super::meta::DiscordTransport;

// ── Shared context ────────────────────────────────────────────────────

/// Shared context for the Discord bot, used by both the Gateway listener
/// and any future webhook handlers.
pub struct DiscordContext {
    /// Shared services bundle (project root, agent pool, bot identity, permissions).
    pub services: Arc<Services>,
    pub bot_token: String,
    pub transport: Arc<DiscordTransport>,
    /// Per-channel conversation history for LLM passthrough.
    pub history: DiscordConversationHistory,
    /// Maximum number of conversation entries to keep per channel.
    pub history_size: usize,
    /// Allowed channel IDs (messages from other channels are ignored).
    pub channel_ids: HashSet<String>,
    /// Allowed Discord user IDs.  When non-empty, only listed users can
    /// interact with the bot.  When empty, all users are allowed.
    pub allowed_users: HashSet<String>,
}

// ── Incoming message dispatch ───────────────────────────────────────────

pub(super) async fn handle_incoming_message(
    ctx: &DiscordContext,
    channel: &str,
    user: &str,
    message: &str,
) {
    use crate::chat::commands::{CommandDispatch, try_handle_command};

    // If there is a pending permission prompt for this channel, interpret the
    // message as a yes/no response.
    {
        if let Some(tx) = ctx
            .services
            .pending_perm_replies
            .resolve_oldest(channel)
            .await
        {
            let decision = if is_permission_approval(message) {
                PermissionDecision::Approve
            } else {
                PermissionDecision::Deny
            };
            let _ = tx.send(decision);
            let confirmation = if decision == PermissionDecision::Approve {
                "Permission approved."
            } else {
                "Permission denied."
            };
            let formatted = markdown_to_discord(confirmation);
            let _ = ctx.transport.send_message(channel, &formatted, "").await;
            return;
        }
    }

    let dispatch = CommandDispatch {
        services: &ctx.services,
        project_root: &ctx.services.project_root,
        bot_user_id: &ctx.services.bot_user_id,
        room_id: channel,
    };

    if let Some(response) = try_handle_command(&dispatch, message) {
        slog!("[discord] Sending command response to {channel}");
        let response = markdown_to_discord(&response);
        if let Err(e) = ctx.transport.send_message(channel, &response, "").await {
            slog!("[discord] Failed to send reply to {channel}: {e}");
        }
        return;
    }

    // Check for async commands (htop, delete).
    if let Some(htop_cmd) = crate::chat::transport::matrix::htop::extract_htop_command(
        message,
        &ctx.services.bot_name,
        &ctx.services.bot_user_id,
    ) {
        use crate::chat::transport::matrix::htop::HtopCommand;
        slog!("[discord] Handling htop command from {user} in {channel}");
        match htop_cmd {
            HtopCommand::Stop => {
                let _ = ctx
                    .transport
                    .send_message(channel, "htop stopped.", "")
                    .await;
            }
            HtopCommand::Start { duration_secs } => {
                let snapshot = crate::chat::transport::matrix::htop::build_htop_message(
                    &ctx.services.agents,
                    0,
                    duration_secs,
                );
                let snapshot = markdown_to_discord(&snapshot);
                let msg_id = match ctx.transport.send_message(channel, &snapshot, "").await {
                    Ok(id) => id,
                    Err(e) => {
                        slog!("[discord] Failed to send htop message: {e}");
                        return;
                    }
                };
                let transport = Arc::clone(&ctx.transport) as Arc<dyn ChatTransport>;
                let agents = Arc::clone(&ctx.services.agents);
                let ch = channel.to_string();
                tokio::spawn(async move {
                    let interval = std::time::Duration::from_secs(2);
                    let total_ticks = (duration_secs as usize) / 2;
                    for tick in 1..=total_ticks {
                        tokio::time::sleep(interval).await;
                        let updated = crate::chat::transport::matrix::htop::build_htop_message(
                            &agents,
                            (tick * 2) as u32,
                            duration_secs,
                        );
                        let updated = markdown_to_discord(&updated);
                        if let Err(e) = transport.edit_message(&ch, &msg_id, &updated, "").await {
                            slog!("[discord] Failed to edit htop message: {e}");
                            break;
                        }
                    }
                });
            }
        }
        return;
    }

    if let Some(del_cmd) = crate::chat::transport::matrix::delete::extract_delete_command(
        message,
        &ctx.services.bot_name,
        &ctx.services.bot_user_id,
    ) {
        let response = match del_cmd {
            crate::chat::transport::matrix::delete::DeleteCommand::Delete { story_number } => {
                slog!("[discord] Handling delete command from {user}: story {story_number}");
                crate::chat::transport::matrix::delete::handle_delete(
                    &ctx.services.bot_name,
                    &story_number,
                    &ctx.services.project_root,
                    &ctx.services.agents,
                )
                .await
            }
            crate::chat::transport::matrix::delete::DeleteCommand::BadArgs => {
                format!("Usage: `{} delete <number>`", ctx.services.bot_name)
            }
        };
        let response = markdown_to_discord(&response);
        let _ = ctx.transport.send_message(channel, &response, "").await;
        return;
    }

    if let Some(rmtree_cmd) = crate::chat::transport::matrix::rmtree::extract_rmtree_command(
        message,
        &ctx.services.bot_name,
        &ctx.services.bot_user_id,
    ) {
        let response = match rmtree_cmd {
            crate::chat::transport::matrix::rmtree::RmtreeCommand::Rmtree { story_number } => {
                slog!(
                    "[discord] Handling rmtree command from {user} in {channel}: story {story_number}"
                );
                crate::chat::transport::matrix::rmtree::handle_rmtree(
                    &ctx.services.bot_name,
                    &story_number,
                    &ctx.services.project_root,
                    &ctx.services.agents,
                )
                .await
            }
            crate::chat::transport::matrix::rmtree::RmtreeCommand::BadArgs => {
                format!("Usage: `{} rmtree <number>`", ctx.services.bot_name)
            }
        };
        let response = markdown_to_discord(&response);
        let _ = ctx.transport.send_message(channel, &response, "").await;
        return;
    }

    if crate::chat::transport::matrix::reset::extract_reset_command(
        message,
        &ctx.services.bot_name,
        &ctx.services.bot_user_id,
    )
    .is_some()
    {
        slog!("[discord] Handling reset command from {user} in {channel}");
        {
            let mut guard = ctx.history.lock().await;
            let conv = guard
                .entry(channel.to_string())
                .or_insert_with(RoomConversation::default);
            conv.session_id = None;
            conv.entries.clear();
            save_discord_history(&ctx.services.project_root, &guard);
        }
        let _ = ctx
            .transport
            .send_message(channel, "Session cleared.", "")
            .await;
        return;
    }

    if crate::chat::compact::extract_compact_command(
        message,
        &ctx.services.bot_name,
        &ctx.services.bot_user_id,
    )
    .is_some()
    {
        slog!("[discord] Handling compact command from {user} in {channel}");
        let response = crate::chat::compact::handle_compact_for_key(
            channel,
            &ctx.history,
            &ctx.services.project_root,
            8_000,
            save_discord_history,
        )
        .await;
        let response = markdown_to_discord(&response);
        let _ = ctx.transport.send_message(channel, &response, "").await;
        return;
    }

    if let Some(start_cmd) = crate::chat::transport::matrix::start::extract_start_command(
        message,
        &ctx.services.bot_name,
        &ctx.services.bot_user_id,
    ) {
        let response = match start_cmd {
            crate::chat::transport::matrix::start::StartCommand::Start {
                story_number,
                agent_hint,
            } => {
                slog!(
                    "[discord] Handling start command from {user} in {channel}: story {story_number}"
                );
                crate::chat::transport::matrix::start::handle_start(
                    &ctx.services.bot_name,
                    &story_number,
                    agent_hint.as_deref(),
                    &ctx.services.project_root,
                    &ctx.services.agents,
                )
                .await
            }
            crate::chat::transport::matrix::start::StartCommand::BadArgs => {
                format!("Usage: `{} start <number>`", ctx.services.bot_name)
            }
        };
        let response = markdown_to_discord(&response);
        let _ = ctx.transport.send_message(channel, &response, "").await;
        return;
    }

    if let Some(assign_cmd) = crate::chat::transport::matrix::assign::extract_assign_command(
        message,
        &ctx.services.bot_name,
        &ctx.services.bot_user_id,
    ) {
        let response = match assign_cmd {
            crate::chat::transport::matrix::assign::AssignCommand::Assign {
                story_number,
                model,
            } => {
                slog!(
                    "[discord] Handling assign command from {user} in {channel}: story {story_number} model {model}"
                );
                crate::chat::transport::matrix::assign::handle_assign(
                    &ctx.services.bot_name,
                    &story_number,
                    &model,
                    &ctx.services.project_root,
                    &ctx.services.agents,
                )
                .await
            }
            crate::chat::transport::matrix::assign::AssignCommand::BadArgs => {
                format!("Usage: `{} assign <number> <model>`", ctx.services.bot_name)
            }
        };
        let response = markdown_to_discord(&response);
        let _ = ctx.transport.send_message(channel, &response, "").await;
        return;
    }

    // No command matched — forward to LLM for conversational response.
    slog!("[discord] No command matched, forwarding to LLM for {user} in {channel}");
    handle_llm_message(ctx, channel, user, message).await;
}

/// Build the prompt for a Discord LLM turn, prepending any pending
/// CRDT pipeline-transition events as a `<system-reminder>` block.
fn build_discord_llm_prompt(
    persona: &str,
    bot_name: &str,
    user: &str,
    user_message: &str,
) -> String {
    let event_ctx = crate::llm_session::assemble_prompt_context(persona);
    format!(
        "{event_ctx}[Your name is {bot_name}. Refer to yourself as {bot_name}, not Claude.]\n\n{user}: {user_message}"
    )
}

/// Forward a message to Claude Code and send the response back via Discord.
async fn handle_llm_message(ctx: &DiscordContext, channel: &str, user: &str, user_message: &str) {
    use crate::chat::util::drain_complete_paragraphs;
    use crate::llm::providers::claude_code::{ClaudeCodeProvider, ClaudeCodeResult};
    use std::sync::atomic::{AtomicBool, Ordering};
    use tokio::sync::watch;

    // Look up existing session ID for this channel.
    let resume_session_id: Option<String> = {
        let guard = ctx.history.lock().await;
        guard.get(channel).and_then(|conv| conv.session_id.clone())
    };

    let bot_name = &ctx.services.bot_name;
    let persona = bot_name.to_lowercase();
    let prompt = build_discord_llm_prompt(&persona, bot_name, user, user_message);

    let provider = ClaudeCodeProvider::new();
    let (_cancel_tx, mut cancel_rx) = watch::channel(false);

    // Channel for sending complete chunks to the Discord posting task.
    let (msg_tx, mut msg_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
    let msg_tx_for_callback = msg_tx.clone();

    // Spawn a task to post messages as they arrive.
    let post_transport = Arc::clone(&ctx.transport) as Arc<dyn ChatTransport>;
    let post_channel = channel.to_string();
    let post_task = tokio::spawn(async move {
        while let Some(chunk) = msg_rx.recv().await {
            let formatted = markdown_to_discord(&chunk);
            let _ = post_transport
                .send_message(&post_channel, &formatted, "")
                .await;
        }
    });

    // Shared buffer between the sync token callback and the async scope.
    let buffer = Arc::new(std::sync::Mutex::new(String::new()));
    let buffer_for_callback = Arc::clone(&buffer);
    let sent_any_chunk = Arc::new(AtomicBool::new(false));
    let sent_any_chunk_for_callback = Arc::clone(&sent_any_chunk);

    let project_root_str = ctx.services.project_root.to_string_lossy().to_string();
    let chat_fut = provider.chat_stream(
        &prompt,
        &project_root_str,
        resume_session_id.as_deref(),
        None,
        None,
        &mut cancel_rx,
        move |token| {
            let mut buf = buffer_for_callback.lock().unwrap();
            buf.push_str(token);
            let paragraphs = drain_complete_paragraphs(&mut buf);
            for chunk in paragraphs {
                sent_any_chunk_for_callback.store(true, Ordering::Relaxed);
                let _ = msg_tx_for_callback.send(chunk);
            }
        },
        |_thinking| {},
        |_activity| {},
    );
    tokio::pin!(chat_fut);

    // Register as a permission responder for the duration of this chat turn.
    let (_perm_guard, mut perm_rx) = ctx.services.permission_registry.register();

    let result = loop {
        tokio::select! {
            r = &mut chat_fut => break r,

            Some(perm_fwd) = perm_rx.recv() => {
                let prompt_msg = format!(
                    "**Permission Request**\n\nTool: `{}`\n```json\n{}\n```\n\nReply **yes** to approve or **no** to deny.",
                    perm_fwd.tool_name,
                    serde_json::to_string_pretty(&perm_fwd.tool_input)
                        .unwrap_or_else(|_| perm_fwd.tool_input.to_string()),
                );
                let formatted = markdown_to_discord(&prompt_msg);
                let _ = ctx.transport.send_message(channel, &formatted, "").await;

                // Keyed by request_id (not just channel) so a second
                // concurrent request doesn't drop the first's sender.
                ctx.services
                    .pending_perm_replies
                    .insert(channel.to_string(), perm_fwd.request_id.clone(), perm_fwd.response_tx)
                    .await;

                // Spawn a timeout task: auto-deny if the user does not respond.
                let pending = Arc::clone(&ctx.services.pending_perm_replies);
                let timeout_channel = channel.to_string();
                let timeout_request_id = perm_fwd.request_id.clone();
                let timeout_transport = Arc::clone(&ctx.transport) as Arc<dyn ChatTransport>;
                let timeout_secs = ctx.services.permission_timeout_secs;
                tokio::spawn(async move {
                    tokio::time::sleep(std::time::Duration::from_secs(timeout_secs)).await;
                    if let Some(tx) = pending.remove_by_request_id(&timeout_channel, &timeout_request_id).await {
                        let _ = tx.send(PermissionDecision::Deny);
                        let msg = "Permission request timed out — denied (fail-closed).";
                        let _ = timeout_transport.send_message(&timeout_channel, msg, "").await;
                    }
                });
            }
        }
    };

    // Flush remaining text.
    let remaining = buffer.lock().unwrap().trim().to_string();
    let did_send_any = sent_any_chunk.load(Ordering::Relaxed);

    let (assistant_reply, new_session_id) = match result {
        Ok(ClaudeCodeResult {
            messages,
            session_id,
            ..
        }) => {
            let reply = if !remaining.is_empty() {
                let _ = msg_tx.send(remaining.clone());
                remaining
            } else if !did_send_any {
                let last_text = messages
                    .iter()
                    .rev()
                    .find(|m| m.role == crate::llm::types::Role::Assistant && !m.content.is_empty())
                    .map(|m| m.content.clone())
                    .unwrap_or_default();
                if !last_text.is_empty() {
                    let _ = msg_tx.send(last_text.clone());
                }
                last_text
            } else {
                remaining
            };
            slog!("[discord] session_id from chat_stream: {:?}", session_id);
            (reply, session_id)
        }
        Err(e) => {
            slog!("[discord] LLM error: {e}");
            let err_msg = format!("Error processing your request: {e}");
            let _ = msg_tx.send(err_msg.clone());
            (err_msg, None)
        }
    };

    // Signal the posting task to finish and wait for it.
    drop(msg_tx);
    let _ = post_task.await;

    // Record this exchange in conversation history.
    if !assistant_reply.starts_with("Error processing") {
        let mut guard = ctx.history.lock().await;
        let conv = guard.entry(channel.to_string()).or_default();

        if new_session_id.is_some() {
            conv.session_id = new_session_id;
        }

        conv.entries.push(ConversationEntry {
            role: ConversationRole::User,
            sender: user.to_string(),
            content: user_message.to_string(),
        });
        conv.entries.push(ConversationEntry {
            role: ConversationRole::Assistant,
            sender: String::new(),
            content: assistant_reply,
        });

        // Trim to configured maximum.
        if conv.entries.len() > ctx.history_size {
            let excess = conv.entries.len() - ctx.history_size;
            conv.entries.drain(..excess);
        }

        save_discord_history(&ctx.services.project_root, &guard);
    }
}

// ── Tests ───────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use tokio::sync::Mutex as TokioMutex;

    #[test]
    fn command_dispatches_through_command_registry() {
        use crate::chat::commands::{CommandDispatch, try_handle_command};

        let services = crate::services::Services::new_test(
            std::path::PathBuf::from("/tmp"),
            "Huskies".to_string(),
        );
        let room_id = "123456789".to_string();

        let synthetic = "Huskies status".to_string();

        let dispatch = CommandDispatch {
            services: &services,
            project_root: &services.project_root,
            bot_user_id: "discord-bot",
            room_id: &room_id,
        };

        let result = try_handle_command(&dispatch, &synthetic);
        assert!(
            result.is_some(),
            "status command should produce output via registry"
        );
        assert!(result.unwrap().contains("Pipeline Status"));
    }

    #[test]
    fn reset_command_extracted_from_discord_message() {
        let result = crate::chat::transport::matrix::reset::extract_reset_command(
            "Huskies reset",
            "Huskies",
            "discord-bot",
        );
        assert!(result.is_some(), "'Huskies reset' should be recognised");
    }

    #[test]
    fn start_command_extracted_from_discord_message() {
        let result = crate::chat::transport::matrix::start::extract_start_command(
            "start 42",
            "Huskies",
            "discord-bot",
        );
        assert!(result.is_some(), "plain 'start 42' should be recognised");
        assert_eq!(
            result,
            Some(crate::chat::transport::matrix::start::StartCommand::Start {
                story_number: "42".to_string(),
                agent_hint: None,
            })
        );
    }

    #[test]
    fn assign_command_extracted_from_discord_message() {
        let result = crate::chat::transport::matrix::assign::extract_assign_command(
            "assign 42 opus",
            "Huskies",
            "discord-bot",
        );
        assert!(
            matches!(
                result,
                Some(crate::chat::transport::matrix::assign::AssignCommand::Assign { .. })
            ),
            "plain 'assign 42 opus' should be recognised on Discord"
        );
    }

    #[tokio::test]
    async fn reset_command_clears_discord_session() {
        use crate::chat::transport::matrix::RoomConversation;

        let channel = "123456789";
        let history: DiscordConversationHistory = Arc::new(TokioMutex::new({
            let mut m = HashMap::new();
            m.insert(
                channel.to_string(),
                RoomConversation {
                    session_id: Some("old-session".to_string()),
                    entries: vec![ConversationEntry {
                        role: ConversationRole::User,
                        sender: "user123".to_string(),
                        content: "previous message".to_string(),
                    }],
                    ..Default::default()
                },
            );
            m
        }));

        let tmp = tempfile::tempdir().unwrap();
        let sk = tmp.path().join(".huskies");
        std::fs::create_dir_all(&sk).unwrap();

        {
            let mut guard = history.lock().await;
            let conv = guard
                .entry(channel.to_string())
                .or_insert_with(RoomConversation::default);
            conv.session_id = None;
            conv.entries.clear();
            save_discord_history(tmp.path(), &guard);
        }

        let guard = history.lock().await;
        let conv = guard.get(channel).unwrap();
        assert!(conv.session_id.is_none(), "session_id should be cleared");
        assert!(conv.entries.is_empty(), "entries should be cleared");
    }

    /// AC 4: fire a `TransitionFired` event, simulate a Discord user turn, and
    /// assert the assembled prompt contains the event (end-to-end non-Matrix test).
    #[test]
    fn discord_prompt_includes_transition_event() {
        use crate::pipeline_state::{PipelineEvent, PlanState, Stage, StoryId, TransitionFired};
        crate::crdt_state::init_for_test();

        crate::event_log::log_transition_event(&TransitionFired {
            story_id: StoryId("77_discord_test".to_string()),
            before: Stage::Backlog,
            after: Stage::Coding {
                claim: None,
                plan: PlanState::Missing,
                retries: 0,
            },
            event: PipelineEvent::DepsMet,
            at: chrono::Utc::now(),
        });

        let prompt =
            build_discord_llm_prompt("discord-ch-test", "Timmy", "@alice", "what is the status?");

        assert!(
            prompt.contains("<system-reminder>"),
            "assembled prompt must include system-reminder block; got: {prompt}"
        );
        assert!(
            prompt.contains("77_discord_test"),
            "assembled prompt must contain story id; got: {prompt}"
        );
        assert!(
            prompt.contains("what is the status?"),
            "assembled prompt must contain user message; got: {prompt}"
        );
    }

    /// Regression test for story 1192: `compact` must not be swallowed by the
    /// registry placeholder. Drives the real entrypoint
    /// (`handle_incoming_message`, not `handle_compact_for_key` directly) so a
    /// future regression in the dispatch order is caught, and asserts the
    /// real handler ran: reply mentions the byte-size confirmation, and the
    /// history's session_id/entries were cleared with pending_seed set.
    #[tokio::test]
    async fn compact_command_runs_through_full_dispatch_and_clears_session() {
        use crate::chat::transport::matrix::{
            ConversationEntry, ConversationRole, RoomConversation,
        };
        use std::collections::HashSet;
        use std::sync::Arc;

        let channel = "555444333";
        let session_id = "sess-discord-compact";

        let tmp = tempfile::tempdir().unwrap();
        let project_root = tmp.path().join("project");
        std::fs::create_dir_all(&project_root).unwrap();
        let home = tempfile::tempdir().unwrap();
        // SAFETY: this test owns HOME for its duration; no other test in this
        // process reads HOME concurrently with this call.
        unsafe {
            std::env::set_var("HOME", home.path());
        }
        let transcript_dir =
            crate::chat::compact::transcript::transcript_path(&project_root, session_id)
                .parent()
                .unwrap()
                .to_path_buf();
        std::fs::create_dir_all(&transcript_dir).unwrap();
        let jsonl = r#"{"type":"user","message":{"role":"user","content":"hello"}}
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"hi there"}]}}"#;
        std::fs::write(transcript_dir.join(format!("{session_id}.jsonl")), jsonl).unwrap();

        let history: DiscordConversationHistory = Arc::new(TokioMutex::new({
            let mut m = HashMap::new();
            m.insert(
                channel.to_string(),
                RoomConversation {
                    session_id: Some(session_id.to_string()),
                    entries: vec![ConversationEntry {
                        role: ConversationRole::User,
                        sender: "user123".to_string(),
                        content: "hi".to_string(),
                    }],
                    pending_seed: None,
                    last_compact_suggested_at_ms: None,
                },
            );
            m
        }));

        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("POST", format!("/channels/{channel}/messages").as_str())
            .match_body(mockito::Matcher::Regex(
                "Compacted session context".to_string(),
            ))
            .with_body(r#"{"id": "1"}"#)
            .create_async()
            .await;

        let services =
            crate::services::Services::new_test(project_root.clone(), "Huskies".to_string());
        let ctx = DiscordContext {
            services,
            bot_token: "test-token".to_string(),
            transport: Arc::new(DiscordTransport::with_api_base(
                "test-token".to_string(),
                server.url(),
            )),
            history: history.clone(),
            history_size: 20,
            channel_ids: HashSet::new(),
            allowed_users: HashSet::new(),
        };

        handle_incoming_message(&ctx, channel, "user123", "compact").await;

        mock.assert_async().await;

        let guard = history.lock().await;
        let conv = guard.get(channel).unwrap();
        assert!(
            conv.session_id.is_none(),
            "session_id must be cleared after compact"
        );
        assert!(
            conv.entries.is_empty(),
            "entries must be cleared after compact"
        );
        assert_eq!(
            conv.pending_seed.as_deref(),
            Some("User: hello\nAssistant: hi there"),
            "pending_seed must hold the distilled digest"
        );
    }
}
