//! Matrix handle_message — runs the LLM turn for a verified incoming message and
//! streams the assistant reply back to the room.

use crate::chat::util::drain_complete_paragraphs;
use crate::llm::providers::claude_code::{ClaudeCodeProvider, ClaudeCodeResult};
use crate::slog;
use matrix_sdk::ruma::OwnedRoomId;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync::watch;

use super::super::context::BotContext;
use super::super::format::markdown_to_html;
use super::super::history::{ConversationEntry, ConversationRole, save_history};

use super::format_user_prompt;

pub(in crate::chat::transport::matrix::bot) async fn handle_message(
    room_id_str: String,
    room_id: OwnedRoomId,
    ctx: BotContext,
    sender: String,
    user_message: String,
    mut cancel_rx: watch::Receiver<bool>,
) {
    // Look up the room's existing Claude Code session ID (if any) so we can
    // resume the conversation with structured API messages instead of
    // flattening history into a text prefix.
    let resume_session_id: Option<String> = {
        let guard = ctx.history.lock().await;
        guard.get(&room_id).and_then(|conv| conv.session_id.clone())
    };

    // Drain any pending `compact` seed for this room so it is injected into
    // the prompt exactly once, then persist the cleared state immediately —
    // a crash mid-turn must not cause it to be re-injected on the next try.
    let pending_seed: Option<String> = {
        let mut guard = ctx.history.lock().await;
        let conv = guard.entry(room_id.clone()).or_default();
        let seed = conv.pending_seed.take();
        if seed.is_some() {
            save_history(&ctx.services.project_root, &guard);
        }
        seed
    };
    let seed_prefix = pending_seed
        .as_deref()
        .map(crate::chat::compact::frame_seed_for_prompt)
        .unwrap_or_default();

    // Pull new pipeline-transition events from the CRDT event log for this
    // persona and atomically advance the high-water marks so the same events
    // are not re-injected on the next turn.  All transports share the same
    // persona key so events are visible regardless of which transport handles
    // the next turn.
    let persona = ctx.services.bot_name.to_lowercase();
    let event_log_ctx = crate::llm_session::assemble_prompt_context(&persona);

    // The prompt is just the current message with sender attribution.
    // Prior conversation context is carried by the Claude Code session.
    let bot_name = &ctx.services.bot_name;
    let active_project_ctx = if let Some(ref ap) = ctx.gateway_active_project {
        let name = ap.read().await.clone();
        format!("[Active project: {name}]\n")
    } else {
        String::new()
    };
    let prompt = format!(
        "{event_log_ctx}{seed_prefix}[Your name is {bot_name}. Refer to yourself as {bot_name}, not Claude.]\n{active_project_ctx}\n{}",
        format_user_prompt(&sender, &user_message)
    );

    let provider = ClaudeCodeProvider::new();

    // Channel for sending complete paragraphs to the Matrix 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 via the transport as they arrive so we
    // don't block the LLM stream while waiting for send round-trips.
    let post_transport = Arc::clone(&ctx.transport);
    let post_room_id = room_id_str.clone();
    let sent_ids = Arc::clone(&ctx.bot_sent_event_ids);
    let sent_ids_for_post = Arc::clone(&sent_ids);
    let post_task = tokio::spawn(async move {
        while let Some(chunk) = msg_rx.recv().await {
            let html = markdown_to_html(&chunk);
            if let Ok(msg_id) = post_transport
                .send_message(&post_room_id, &chunk, &html)
                .await
                && let Ok(event_id) = msg_id.parse()
            {
                sent_ids_for_post.lock().await.insert(event_id);
            }
        }
    });

    // Shared state between the sync token callback and the async outer 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);

    // In gateway mode, run Claude Code in the gateway config directory so it
    // picks up the `.mcp.json` that points to the gateway's MCP proxy endpoint.
    // The gateway proxies tool calls to the active project automatically.
    // In standalone mode, use the project root directly.
    let project_root_str = if ctx.is_gateway() {
        ctx.services.project_root.to_string_lossy().to_string()
    } else {
        ctx.effective_project_root()
            .await
            .to_string_lossy()
            .to_string()
    };
    let chat_fut = provider.chat_stream(
        &prompt,
        &project_root_str,
        resume_session_id.as_deref(),
        None,
        ctx.model.as_deref(),
        &mut cancel_rx,
        move |token| {
            let mut buf = buffer_for_callback.lock().unwrap();
            buf.push_str(token);
            // Flush complete paragraphs as they arrive.
            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| {}, // Discard thinking tokens
        |_activity| {}, // Discard activity signals
    );
    tokio::pin!(chat_fut);

    // Permission requests are handled by the persistent permission_listener
    // task spawned at bot startup (story 884) — they no longer route through
    // per-message handlers. Just await chat_fut.
    let result = (&mut chat_fut).await;

    // Flush any remaining text that didn't end with a paragraph boundary.
    let remaining = buffer.lock().unwrap().trim().to_string();
    let did_send_any = sent_any_chunk.load(Ordering::Relaxed);

    let (assistant_reply, new_session_id, turn_usage) = match result {
        Ok(ClaudeCodeResult {
            messages,
            session_id,
            usage,
        }) => {
            let reply = if !remaining.is_empty() {
                let _ = msg_tx.send(remaining.clone());
                remaining
            } else if !did_send_any {
                // Nothing was streamed at all (e.g. only tool calls with no
                // final text) — fall back to the last assistant message from
                // the structured result.
                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!("[matrix-bot] session_id from chat_stream: {:?}", session_id);
            (reply, session_id, usage)
        }
        Err(e) => {
            slog!("[matrix-bot] LLM error: {e}");
            let err_msg = if let Some(url) = crate::llm::oauth::extract_login_url_from_error(&e) {
                format!("Authentication required. [Click here to log in to Claude]({url})")
            } else {
                format!("Error processing your request: {e}")
            };
            let _ = msg_tx.send(err_msg.clone());
            (err_msg, None, None)
        }
    };

    // Drop the sender to signal the posting task that no more messages will
    // arrive, then wait for all pending Matrix sends to complete.
    drop(msg_tx);
    let _ = post_task.await;

    // Record this exchange in the per-room conversation history and persist
    // the session ID so the next turn resumes with structured API messages.
    let mut compact_suggestion: Option<String> = None;
    if !assistant_reply.starts_with("Error processing") {
        let mut guard = ctx.history.lock().await;
        let conv = guard.entry(room_id.clone()).or_default();

        // Store the session ID so the next turn uses --resume.
        slog!(
            "[matrix-bot] storing session_id: {:?} (was: {:?})",
            new_session_id,
            conv.session_id
        );
        if new_session_id.is_some() {
            conv.session_id = new_session_id;
        }

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

        // Trim to the configured maximum, dropping the oldest entries first.
        // The session_id is preserved: Claude Code's --resume loads the full
        // conversation from its own session transcript on disk, so trimming
        // our local tracking doesn't affect the LLM's context.
        if conv.entries.len() > ctx.history_size {
            let excess = conv.entries.len() - ctx.history_size;
            conv.entries.drain(..excess);
        }

        // When this turn's cache_read usage crosses the configured threshold,
        // queue a rate-limited suggestion to run `compact`. Rate-limited via
        // `last_compact_suggested_at_ms` so a busy room isn't nagged every turn.
        if let Some(usage) = &turn_usage
            && usage.cache_read_input_tokens > ctx.cache_read_suggest_threshold
        {
            let now_ms = chrono::Utc::now().timestamp_millis();
            let cooldown_ms = ctx.compact_suggest_cooldown_secs.saturating_mul(1_000);
            let due = conv
                .last_compact_suggested_at_ms
                .is_none_or(|last| now_ms - last >= cooldown_ms);
            if due {
                conv.last_compact_suggested_at_ms = Some(now_ms);
                compact_suggestion = Some(format!(
                    "This turn read {} cache tokens. Consider running `compact` to distill the \
                     session and reduce context size.",
                    usage.cache_read_input_tokens
                ));
            }
        }

        // Persist to disk so history survives server restarts.
        save_history(&ctx.services.project_root, &guard);
    } else {
        // Clear session_id on error so a poisoned session (e.g. pending
        // tool call with no response) doesn't cause a crash loop on resume.
        let mut guard = ctx.history.lock().await;
        if let Some(conv) = guard.get_mut(&room_id)
            && conv.session_id.is_some()
        {
            slog!("[matrix-bot] clearing session_id after error to prevent crash loop");
            conv.session_id = None;
            save_history(&ctx.services.project_root, &guard);
        }
    }

    if let Some(suggestion) = compact_suggestion {
        let html = markdown_to_html(&suggestion);
        let _ = ctx
            .transport
            .send_message(&room_id_str, &suggestion, &html)
            .await;
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
