use std::{fs, io, path::{Path, PathBuf}};

use ndarray::{Array1, Array2};
use rayon::prelude::*;

use crate::bitvec::{PersistentBitVec, PersistentBitVecBuilder};
use crate::meta::MatrixMeta;

fn col_path(dir: &Path, col: usize) -> PathBuf {
    dir.join(format!("col_{col:06}.pbiv"))
}

pub struct PersistentBitMatrix {
    cols: Vec<PersistentBitVec>,
    n:    usize,
}

impl PersistentBitMatrix {
    pub fn open(dir: &Path) -> io::Result<Self> {
        let meta = MatrixMeta::load(dir)?;
        let cols = (0..meta.n_cols)
            .map(|c| PersistentBitVec::open(&col_path(dir, c)))
            .collect::<io::Result<Vec<_>>>()?;
        Ok(Self { cols, n: meta.n })
    }

    pub fn n(&self)      -> usize { self.n }
    pub fn n_cols(&self) -> usize { self.cols.len() }
    pub fn col(&self, c: usize) -> &PersistentBitVec { &self.cols[c] }

    pub fn row(&self, slot: usize) -> Box<[bool]> {
        self.cols.iter().map(|c| c.get(slot)).collect()
    }

    /// Returns the number of set bits in each column as `Array1<u64>`.
    pub fn count_ones(&self) -> Array1<u64> {
        let counts: Vec<u64> = (0..self.n_cols())
            .into_par_iter()
            .map(|c| self.col(c).count_ones())
            .collect();
        Array1::from_vec(counts)
    }

    // ── Distance matrices ─────────────────────────────────────────────────────

    pub fn jaccard_dist_matrix(&self) -> Array2<f64> {
        self.pairwise_f64(|i, j| self.col(i).jaccard_dist(self.col(j)))
    }

    pub fn hamming_dist_matrix(&self) -> Array2<u64> {
        self.pairwise_u64(|i, j| self.col(i).hamming_dist(self.col(j)))
    }

    // ── Partial matrices (additively decomposable across layers) ──────────────

    /// Returns `(inter[n×n], union[n×n])`.
    /// Reduce across layers by element-wise addition before computing `1 - inter/union`.
    pub fn partial_jaccard_dist_matrix(&self) -> (Array2<u64>, Array2<u64>) {
        let n = self.n_cols();
        let results: Vec<(usize, usize, u64, u64)> = upper_pairs(n)
            .into_par_iter()
            .map(|(i, j)| {
                let (inter, union) = self.col(i).partial_jaccard_dist(self.col(j));
                (i, j, inter, union)
            })
            .collect();

        let mut inter_m = Array2::zeros((n, n));
        let mut union_m = Array2::zeros((n, n));
        for (i, j, inter, union) in results {
            inter_m[[i, j]] = inter; inter_m[[j, i]] = inter;
            union_m[[i, j]] = union; union_m[[j, i]] = union;
        }
        (inter_m, union_m)
    }

    /// Returns `hamming[n×n]` (number of differing bits per pair).
    /// Additive across layers — reduce by element-wise addition.
    pub fn partial_hamming_dist_matrix(&self) -> Array2<u64> {
        self.pairwise_u64(|i, j| self.col(i).hamming_dist(self.col(j)))
    }

    // ── Private helpers ───────────────────────────────────────────────────────

    fn pairwise_f64(&self, f: impl Fn(usize, usize) -> f64 + Sync) -> Array2<f64> {
        let n = self.n_cols();
        let results: Vec<(usize, usize, f64)> = upper_pairs(n)
            .into_par_iter()
            .map(|(i, j)| (i, j, f(i, j)))
            .collect();
        fill_symmetric(n, results.into_iter().map(|(i, j, v)| (i, j, v, v)))
    }

    fn pairwise_u64(&self, f: impl Fn(usize, usize) -> u64 + Sync) -> Array2<u64> {
        let n = self.n_cols();
        let results: Vec<(usize, usize, u64)> = upper_pairs(n)
            .into_par_iter()
            .map(|(i, j)| (i, j, f(i, j)))
            .collect();
        fill_symmetric(n, results.into_iter().map(|(i, j, v)| (i, j, v, v)))
    }
}

// ── Column append ─────────────────────────────────────────────────────────────

impl PersistentBitMatrix {
    /// Append a new column to an existing matrix on disk.
    ///
    /// Reads `meta.json` to obtain `n` and the current column count, writes
    /// `col_{n_cols:06}.pbiv` filled by `value_of(slot)`, then increments
    /// `n_cols` in `meta.json`.
    pub fn append_column(dir: &Path, value_of: impl Fn(usize) -> bool) -> io::Result<()> {
        let mut meta = MatrixMeta::load(dir)?;
        let mut b = PersistentBitVecBuilder::new(meta.n, &col_path(dir, meta.n_cols))?;
        for slot in 0..meta.n {
            b.set(slot, value_of(slot));
        }
        b.close()?;
        meta.n_cols += 1;
        meta.save(dir)
    }
}

fn upper_pairs(n: usize) -> Vec<(usize, usize)> {
    (0..n).flat_map(|i| (i + 1..n).map(move |j| (i, j))).collect()
}

fn fill_symmetric<T>(n: usize, vals: impl Iterator<Item = (usize, usize, T, T)>) -> Array2<T>
where
    T: Clone + Default,
{
    let mut m = Array2::from_elem((n, n), T::default());
    for (i, j, vij, vji) in vals {
        m[[i, j]] = vij;
        m[[j, i]] = vji;
    }
    m
}

// ── Trait impls ───────────────────────────────────────────────────────────────

use crate::traits::{BitPartials, ColumnWeights};

impl ColumnWeights for PersistentBitMatrix {
    fn col_weights(&self) -> Array1<u64> { self.count_ones() }
}

impl BitPartials for PersistentBitMatrix {
    fn partial_jaccard(&self) -> (Array2<u64>, Array2<u64>) {
        self.partial_jaccard_dist_matrix()
    }
    fn partial_hamming(&self) -> Array2<u64> {
        self.partial_hamming_dist_matrix()
    }
}

// ── Builder ───────────────────────────────────────────────────────────────────

pub struct PersistentBitMatrixBuilder {
    dir:    PathBuf,
    n:      usize,
    n_cols: usize,
}

impl PersistentBitMatrixBuilder {
    pub fn new(n: usize, dir: &Path) -> io::Result<Self> {
        fs::create_dir_all(dir)?;
        Ok(Self { dir: dir.to_path_buf(), n, n_cols: 0 })
    }

    pub fn n(&self)      -> usize { self.n }
    pub fn n_cols(&self) -> usize { self.n_cols }

    pub fn add_col(&mut self) -> io::Result<PersistentBitVecBuilder> {
        let path = col_path(&self.dir, self.n_cols);
        self.n_cols += 1;
        PersistentBitVecBuilder::new(self.n, &path)
    }

    pub fn close(self) -> io::Result<()> {
        MatrixMeta { n: self.n, n_cols: self.n_cols }.save(&self.dir)
    }
}
