use crate::localization::{CycleSummaryText, Localizer};
use cosimo::{PromptGuess, RecallFeedback, Review, ReviewPassItem};

#[derive(Debug, Clone, Default)]
pub(crate) enum ReviewSession {
    #[default]
    Ready,
    Running(Box<RunningReviewSession>),
}

impl ReviewSession {
    pub(crate) fn start(
        queue: Vec<usize>,
        deck_len: usize,
        was_scheduled: bool,
        repeat_seed: u64,
        started_at_unix_seconds: i64,
    ) -> Result<Self, EmptyReviewQueue> {
        Ok(Self::Running(Box::new(RunningReviewSession::new(
            queue,
            deck_len,
            was_scheduled,
            repeat_seed,
            started_at_unix_seconds,
        )?)))
    }

    pub(crate) fn is_ready(&self) -> bool {
        matches!(self, Self::Ready)
    }

    pub(crate) fn phase(&self) -> ReviewPhase {
        match self {
            Self::Ready => ReviewPhase::ReadyToStart,
            Self::Running(session) => session.phase(),
        }
    }

    pub(crate) fn queue(&self) -> &[usize] {
        match self {
            Self::Ready => &[],
            Self::Running(session) => session.queue(),
        }
    }

    pub(crate) fn scheduled_card_count(&self) -> usize {
        self.queue().len()
    }

    #[cfg(test)]
    pub(crate) fn stats(&self) -> ReviewCycleStats {
        match self {
            Self::Ready => ReviewCycleStats::default(),
            Self::Running(session) => session.stats(),
        }
    }

    pub(crate) fn current_index(&self) -> usize {
        match self {
            Self::Ready => 0,
            Self::Running(session) => session.current_index(),
        }
    }

    pub(crate) fn current_deck_index(&self) -> Option<usize> {
        match self {
            Self::Ready => None,
            Self::Running(session) => Some(session.current_deck_index()),
        }
    }

    pub(crate) fn show_response(&mut self, guess: PromptGuess) -> bool {
        let Self::Running(session) = self else {
            return false;
        };
        session.show_response(guess);
        true
    }

    pub(crate) fn response_guess(&self) -> Option<PromptGuess> {
        let Self::Running(session) = self else {
            return None;
        };
        session.response_guess()
    }

    pub(crate) fn record_completed_review(
        &mut self,
        review: Review,
        feedback: RecallFeedback,
        review_event_id: i64,
        completed_at_unix_seconds: i64,
    ) -> Option<ReviewProgress> {
        let Self::Running(session) = self else {
            return None;
        };
        Some(session.record_completed_review(
            review,
            feedback,
            review_event_id,
            completed_at_unix_seconds,
        ))
    }

    pub(crate) fn defer_current_prompt(
        &mut self,
        deferred_at_unix_seconds: i64,
    ) -> Option<ReviewDeferralProgress> {
        let Self::Running(session) = self else {
            return None;
        };
        let progress = session.defer_current_prompt(deferred_at_unix_seconds)?;
        if progress.pass_finished() {
            *self = Self::Ready;
        }
        Some(progress)
    }

    pub(crate) fn end_current_pass(
        &mut self,
        ended_at_unix_seconds: i64,
    ) -> Option<ReviewCycleSummary> {
        let Self::Running(session) = self else {
            return None;
        };
        let summary = session.early_summary(ended_at_unix_seconds);
        *self = Self::Ready;
        Some(summary)
    }

    pub(crate) fn reset(&mut self) {
        *self = Self::Ready;
    }
}

#[derive(Debug, Clone)]
pub(crate) struct RunningReviewSession {
    // Running sessions always have at least one queued card. Keeping that
    // invariant in ReviewQueue lets the review flow index the current card
    // directly without scattering empty-queue checks through the UI handlers.
    queue: ReviewQueue,
    initial_queue_len: usize,
    failure_repeats_queued: Vec<bool>,
    reviewed_cards_seen: Vec<bool>,
    review_items: Vec<ReviewPassItem>,
    repeat_shuffle_state: u64,
    started_at_unix_seconds: i64,
    phase: RunningReviewPhase,
    stats: ReviewCycleStats,
    was_scheduled: bool,
}

impl RunningReviewSession {
    fn new(
        queue: Vec<usize>,
        deck_len: usize,
        was_scheduled: bool,
        repeat_seed: u64,
        started_at_unix_seconds: i64,
    ) -> Result<Self, EmptyReviewQueue> {
        let initial_queue_len = queue.len();
        Ok(Self {
            queue: ReviewQueue::new(queue)?,
            initial_queue_len,
            failure_repeats_queued: vec![false; deck_len],
            reviewed_cards_seen: vec![false; deck_len],
            review_items: Vec::new(),
            repeat_shuffle_state: repeat_seed ^ 0x8b8b_8b8b_8b8b_8b8b,
            started_at_unix_seconds,
            phase: RunningReviewPhase::Prompt,
            stats: ReviewCycleStats::default(),
            was_scheduled,
        })
    }

    fn phase(&self) -> ReviewPhase {
        match self.phase {
            RunningReviewPhase::Prompt => ReviewPhase::Prompt,
            RunningReviewPhase::Response { guess } => ReviewPhase::Response { guess },
        }
    }

    fn queue(&self) -> &[usize] {
        self.queue.as_slice()
    }

    fn current_index(&self) -> usize {
        self.queue.current_index()
    }

    #[cfg(test)]
    fn stats(&self) -> ReviewCycleStats {
        self.stats
    }

    fn current_deck_index(&self) -> usize {
        self.queue.current_deck_index()
    }

    fn show_response(&mut self, guess: PromptGuess) {
        self.phase = RunningReviewPhase::Response { guess };
    }

    fn response_guess(&self) -> Option<PromptGuess> {
        match self.phase {
            RunningReviewPhase::Response { guess } => Some(guess),
            RunningReviewPhase::Prompt => None,
        }
    }

    fn record_completed_review(
        &mut self,
        review: Review,
        feedback: RecallFeedback,
        review_event_id: i64,
        completed_at_unix_seconds: i64,
    ) -> ReviewProgress {
        let deck_index = self.current_deck_index();
        let completed_index = self.queue.completed_index();
        let is_unique_card = self.mark_card_reviewed(deck_index);
        self.stats.record(review, is_unique_card);
        self.review_items.push(ReviewPassItem::new(
            review_event_id,
            completed_index,
            !is_unique_card,
        ));
        self.queue_failed_card_repeat(deck_index, feedback);
        let total_cards = self.queue.len();
        let finished_cycle = completed_index == total_cards;
        self.queue.advance();
        self.phase = RunningReviewPhase::Prompt;

        ReviewProgress {
            completed_index,
            total_cards,
            completed_summary: finished_cycle.then_some(ReviewCycleSummary {
                stats: self.stats,
                total_cards,
                initial_cards: self.initial_queue_len,
                started_at_unix_seconds: self.started_at_unix_seconds,
                finished_at_unix_seconds: self
                    .finished_at_unix_seconds_at(completed_at_unix_seconds),
                elapsed_seconds: self.elapsed_seconds_at(completed_at_unix_seconds),
                ended_early: false,
                was_scheduled: self.was_scheduled,
                items: self.review_items.clone(),
            }),
        }
    }

    fn defer_current_prompt(
        &mut self,
        deferred_at_unix_seconds: i64,
    ) -> Option<ReviewDeferralProgress> {
        if self.phase != RunningReviewPhase::Prompt {
            return None;
        }

        let removed_from_initial_queue = self.queue.current_index() < self.initial_queue_len;
        let removed_last_queued_card = self.queue.remove_current();
        if removed_from_initial_queue {
            self.initial_queue_len = self.initial_queue_len.saturating_sub(1);
        }

        if self.queue.is_empty() || removed_last_queued_card {
            let completed_summary = (self.stats.reviewed_cards > 0).then(|| ReviewCycleSummary {
                stats: self.stats,
                total_cards: self.queue.len(),
                initial_cards: self.initial_queue_len,
                started_at_unix_seconds: self.started_at_unix_seconds,
                finished_at_unix_seconds: self
                    .finished_at_unix_seconds_at(deferred_at_unix_seconds),
                elapsed_seconds: self.elapsed_seconds_at(deferred_at_unix_seconds),
                ended_early: false,
                was_scheduled: self.was_scheduled,
                items: self.review_items.clone(),
            });
            return Some(ReviewDeferralProgress::Finished { completed_summary });
        }

        Some(ReviewDeferralProgress::Continuing)
    }

    fn mark_card_reviewed(&mut self, deck_index: usize) -> bool {
        let Some(already_seen) = self.reviewed_cards_seen.get_mut(deck_index) else {
            return false;
        };
        if *already_seen {
            false
        } else {
            *already_seen = true;
            true
        }
    }

    fn queue_failed_card_repeat(&mut self, deck_index: usize, feedback: RecallFeedback) {
        if feedback != RecallFeedback::Again {
            return;
        }

        if let Some(already_queued) = self.failure_repeats_queued.get_mut(deck_index)
            && !*already_queued
        {
            *already_queued = true;
            let repeat_count = self.queue.len().saturating_sub(self.initial_queue_len);
            let repeat_offset =
                (splitmix64(&mut self.repeat_shuffle_state) as usize) % (repeat_count + 1);
            self.queue
                .insert(self.initial_queue_len + repeat_offset, deck_index);
        }
    }

    fn early_summary(&self, ended_at_unix_seconds: i64) -> ReviewCycleSummary {
        ReviewCycleSummary {
            stats: self.stats,
            total_cards: self.queue.len(),
            initial_cards: self.initial_queue_len,
            started_at_unix_seconds: self.started_at_unix_seconds,
            finished_at_unix_seconds: self.finished_at_unix_seconds_at(ended_at_unix_seconds),
            elapsed_seconds: self.elapsed_seconds_at(ended_at_unix_seconds),
            ended_early: true,
            was_scheduled: self.was_scheduled,
            items: self.review_items.clone(),
        }
    }

    fn elapsed_seconds_at(&self, ended_at_unix_seconds: i64) -> u64 {
        self.finished_at_unix_seconds_at(ended_at_unix_seconds)
            .saturating_sub(self.started_at_unix_seconds) as u64
    }

    fn finished_at_unix_seconds_at(&self, ended_at_unix_seconds: i64) -> i64 {
        ended_at_unix_seconds.max(self.started_at_unix_seconds)
    }
}

#[derive(Debug, Clone)]
struct ReviewQueue {
    cards: Vec<usize>,
    current_index: usize,
}

impl ReviewQueue {
    fn new(cards: Vec<usize>) -> Result<Self, EmptyReviewQueue> {
        if cards.is_empty() {
            return Err(EmptyReviewQueue);
        }

        Ok(Self {
            cards,
            current_index: 0,
        })
    }

    fn as_slice(&self) -> &[usize] {
        &self.cards
    }

    fn len(&self) -> usize {
        self.cards.len()
    }

    fn is_empty(&self) -> bool {
        self.cards.is_empty()
    }

    fn current_index(&self) -> usize {
        self.current_index
    }

    fn completed_index(&self) -> usize {
        self.current_index + 1
    }

    fn current_deck_index(&self) -> usize {
        self.cards[self.current_index]
    }

    fn insert(&mut self, index: usize, deck_index: usize) {
        self.cards.insert(index, deck_index);
    }

    fn remove_current(&mut self) -> bool {
        let removed_index = self.current_index;
        self.cards.remove(removed_index);
        removed_index >= self.cards.len()
    }

    fn advance(&mut self) {
        self.current_index = (self.current_index + 1) % self.cards.len();
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RunningReviewPhase {
    Prompt,
    Response { guess: PromptGuess },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ReviewPhase {
    ReadyToStart,
    Prompt,
    Response { guess: PromptGuess },
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct ReviewCycleStats {
    pub(crate) reviewed_cards: usize,
    pub(crate) unique_reviewed_cards: usize,
    pub(crate) prompt_guess_counts: [usize; 5],
    pub(crate) recall_feedback_counts: [usize; 4],
}

impl ReviewCycleStats {
    pub(crate) fn record(&mut self, review: Review, is_unique_card: bool) {
        self.reviewed_cards += 1;
        if is_unique_card {
            self.unique_reviewed_cards += 1;
        }
        self.prompt_guess_counts[usize::from(review.prompt_guess().value())] += 1;
        self.recall_feedback_counts[rating_index(review.recall_feedback().value())] += 1;
    }

    pub(crate) fn summary_text(
        &self,
        localizer: Localizer,
        total_cards: usize,
        elapsed_seconds: u64,
        ended_early: bool,
        was_scheduled: bool,
    ) -> String {
        localizer.cycle_summary_text(CycleSummaryText {
            reviewed_cards: self.reviewed_cards,
            unique_reviewed_cards: self.unique_reviewed_cards,
            total_cards,
            elapsed_seconds,
            ended_early,
            was_scheduled,
            prompt_guess_counts: self.prompt_guess_counts,
            recall_feedback_counts: self.recall_feedback_counts,
        })
    }
}

#[derive(Debug, Clone)]
pub(crate) struct ReviewCycleSummary {
    pub(crate) stats: ReviewCycleStats,
    pub(crate) total_cards: usize,
    pub(crate) initial_cards: usize,
    pub(crate) started_at_unix_seconds: i64,
    pub(crate) finished_at_unix_seconds: i64,
    pub(crate) elapsed_seconds: u64,
    pub(crate) ended_early: bool,
    pub(crate) was_scheduled: bool,
    pub(crate) items: Vec<ReviewPassItem>,
}

#[derive(Debug, Clone)]
pub(crate) struct ReviewProgress {
    pub(crate) completed_index: usize,
    pub(crate) total_cards: usize,
    pub(crate) completed_summary: Option<ReviewCycleSummary>,
}

#[derive(Debug, Clone)]
pub(crate) enum ReviewDeferralProgress {
    Continuing,
    Finished {
        completed_summary: Option<ReviewCycleSummary>,
    },
}

impl ReviewDeferralProgress {
    pub(crate) fn pass_finished(&self) -> bool {
        matches!(self, Self::Finished { .. })
    }

    pub(crate) fn completed_summary(&self) -> Option<&ReviewCycleSummary> {
        match self {
            Self::Finished {
                completed_summary: Some(summary),
            } => Some(summary),
            Self::Continuing
            | Self::Finished {
                completed_summary: None,
            } => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct EmptyReviewQueue;

#[cfg(test)]
pub(crate) fn format_count_and_percentage(count: usize, total: usize) -> String {
    if total == 0 {
        return format!("{count} (0.0%)");
    }

    let percentage = (count as f64 / total as f64) * 100.0;
    format!("{count} ({percentage:.1}%)")
}

fn rating_index(value: u8) -> usize {
    usize::from(value.saturating_sub(1))
}

fn splitmix64(state: &mut u64) -> u64 {
    *state = state.wrapping_add(0x9e3779b97f4a7c15);
    let mut value = *state;
    value = (value ^ (value >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
    value = (value ^ (value >> 27)).wrapping_mul(0x94d049bb133111eb);
    value ^ (value >> 31)
}
