//! Core sequence-checking logic.
//! Receives values in order of appearance and detects issues by comparing
//! the difference from the previous value against the expected step.

use serde::Serialize;

/// Range of expected values skipped in the step direction
/// (both ends inclusive, spaced by step).
/// `count` is the number of missing values contained in the range.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct MissingRange {
    pub first: i128,
    pub last: i128,
    pub count: u128,
}

/// A single issue detected by the sequence check.
/// `row` is the 1-based line number in the input file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Issue {
    /// Same value as the previous row.
    Duplicate { row: u64, value: i128 },
    /// A jump in the step direction. `missing` is the range of skipped expected values.
    Gap {
        row: u64,
        expected: i128,
        actual: i128,
        missing: MissingRange,
    },
    /// A change inconsistent with the step (backwards, or off the step grid).
    OrderViolation {
        row: u64,
        expected: i128,
        actual: i128,
    },
}

impl Issue {
    pub fn row(&self) -> u64 {
        match self {
            Issue::Duplicate { row, .. }
            | Issue::Gap { row, .. }
            | Issue::OrderViolation { row, .. } => *row,
        }
    }
}

/// Aggregated check result. The sequence is valid when `issues` is empty.
#[derive(Debug, Default)]
pub struct CheckReport {
    pub rows: u64,
    pub start: Option<i128>,
    pub end: Option<i128>,
    pub issues: Vec<Issue>,
}

impl CheckReport {
    pub fn is_ok(&self) -> bool {
        self.issues.is_empty()
    }

    pub fn missing_ranges(&self) -> Vec<MissingRange> {
        self.issues
            .iter()
            .filter_map(|i| match i {
                Issue::Gap { missing, .. } => Some(*missing),
                _ => None,
            })
            .collect()
    }

    /// Total number of missing values (sum of `missing` counts across all gaps).
    pub fn missing_total(&self) -> u128 {
        self.missing_ranges()
            .iter()
            .fold(0u128, |acc, r| acc.saturating_add(r.count))
    }

    pub fn duplicate_values(&self) -> Vec<i128> {
        self.issues
            .iter()
            .filter_map(|i| match i {
                Issue::Duplicate { value, .. } => Some(*value),
                _ => None,
            })
            .collect()
    }
}

/// Appearance-order sequence checker. Feed values one by one with `push`,
/// then obtain the aggregated result with `finish`.
pub struct Checker {
    step: i128,
    prev: Option<i128>,
    report: CheckReport,
}

impl Checker {
    /// `step` must be non-zero (assumed validated by the caller).
    pub fn new(step: i128) -> Self {
        debug_assert!(step != 0);
        Self {
            step,
            prev: None,
            report: CheckReport::default(),
        }
    }

    pub fn push(&mut self, row: u64, value: i128) {
        self.report.rows += 1;
        self.report.end = Some(value);
        let Some(prev) = self.prev.replace(value) else {
            self.report.start = Some(value);
            return;
        };
        let expected = prev.saturating_add(self.step);
        if value == expected {
            return;
        }
        if value == prev {
            self.report.issues.push(Issue::Duplicate { row, value });
            return;
        }
        match self.missing_between(prev, value) {
            Some(missing) => self.report.issues.push(Issue::Gap {
                row,
                expected,
                actual: value,
                missing,
            }),
            None => self.report.issues.push(Issue::OrderViolation {
                row,
                expected,
                actual: value,
            }),
        }
    }

    /// Returns the range of skipped expected values when the change from
    /// `prev` to `value` is a jump in the step direction. Returns `None` for
    /// backward moves or changes smaller than the step.
    fn missing_between(&self, prev: i128, value: i128) -> Option<MissingRange> {
        let diff = value.checked_sub(prev)?;
        if (diff > 0) != (self.step > 0) {
            return None;
        }
        let skipped = (diff.unsigned_abs() - 1) / self.step.unsigned_abs();
        if skipped == 0 {
            return None;
        }
        let first = prev.checked_add(self.step)?;
        let offset = i128::try_from(skipped).ok()?.checked_mul(self.step)?;
        let last = prev.checked_add(offset)?;
        Some(MissingRange {
            first,
            last,
            count: skipped,
        })
    }

    pub fn finish(self) -> CheckReport {
        self.report
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn check(step: i128, values: &[i128]) -> CheckReport {
        let mut c = Checker::new(step);
        for (i, &v) in values.iter().enumerate() {
            c.push(i as u64 + 1, v);
        }
        c.finish()
    }

    #[test]
    fn ascending_step1_is_ok() {
        let r = check(1, &[0, 1, 2, 3]);
        assert!(r.is_ok());
        assert_eq!(r.rows, 4);
        assert_eq!(r.start, Some(0));
        assert_eq!(r.end, Some(3));
    }

    #[test]
    fn empty_input_is_ok() {
        let r = check(1, &[]);
        assert!(r.is_ok());
        assert_eq!(r.rows, 0);
        assert_eq!(r.start, None);
        assert_eq!(r.end, None);
    }

    #[test]
    fn single_value_is_ok() {
        let r = check(1, &[42]);
        assert!(r.is_ok());
        assert_eq!(r.start, Some(42));
        assert_eq!(r.end, Some(42));
    }

    #[test]
    fn detects_duplicate() {
        let r = check(1, &[1, 2, 2, 3]);
        assert_eq!(r.issues, vec![Issue::Duplicate { row: 3, value: 2 }]);
        assert_eq!(r.duplicate_values(), vec![2]);
    }

    #[test]
    fn detects_gap_with_missing_range() {
        let r = check(1, &[0, 1, 2, 5]);
        assert_eq!(
            r.issues,
            vec![Issue::Gap {
                row: 4,
                expected: 3,
                actual: 5,
                missing: MissingRange {
                    first: 3,
                    last: 4,
                    count: 2,
                },
            }]
        );
        assert_eq!(
            r.missing_ranges(),
            vec![MissingRange {
                first: 3,
                last: 4,
                count: 2,
            }]
        );
        assert_eq!(r.missing_total(), 2);
    }

    #[test]
    fn gap_with_step2_reports_aligned_missing() {
        let r = check(2, &[0, 2, 8]);
        assert_eq!(
            r.issues,
            vec![Issue::Gap {
                row: 3,
                expected: 4,
                actual: 8,
                missing: MissingRange {
                    first: 4,
                    last: 6,
                    count: 2,
                },
            }]
        );
    }

    #[test]
    fn off_grid_value_is_order_violation() {
        let r = check(10, &[0, 5]);
        assert_eq!(
            r.issues,
            vec![Issue::OrderViolation {
                row: 2,
                expected: 10,
                actual: 5,
            }]
        );
    }

    #[test]
    fn descending_step_is_supported() {
        let r = check(-1, &[5, 4, 3]);
        assert!(r.is_ok());
    }

    #[test]
    fn descending_gap_reports_missing_in_step_direction() {
        let r = check(-1, &[5, 2]);
        assert_eq!(
            r.issues,
            vec![Issue::Gap {
                row: 2,
                expected: 4,
                actual: 2,
                missing: MissingRange {
                    first: 4,
                    last: 3,
                    count: 2,
                },
            }]
        );
    }

    #[test]
    fn backward_jump_is_order_violation() {
        let r = check(1, &[5, 3]);
        assert_eq!(
            r.issues,
            vec![Issue::OrderViolation {
                row: 2,
                expected: 6,
                actual: 3,
            }]
        );
    }

    #[test]
    fn multiple_issues_are_all_reported() {
        let r = check(1, &[0, 0, 3, 2]);
        assert_eq!(r.issues.len(), 3);
        assert!(!r.is_ok());
    }
}
