use std::fs::{self, File};
use std::io::{self, Write as _};
use std::path::{Path, PathBuf};

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

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

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

// ── ColumnarBitMatrix ─────────────────────────────────────────────────────────

/// Per-column file layout (original format).
pub struct ColumnarBitMatrix {
    cols: Vec<PersistentBitVec>,
    n:    usize,
}

impl ColumnarBitMatrix {
    pub(crate) 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(crate) fn n(&self)      -> usize { self.n }
    pub(crate) fn n_cols(&self) -> usize { self.cols.len() }
    pub(crate) fn col(&self, c: usize) -> &PersistentBitVec { &self.cols[c] }

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

    pub(crate) fn fill_row(&self, slot: usize, buf: &mut [u32]) {
        for (c, col) in self.cols.iter().enumerate() {
            buf[c] = col.get(slot) as u32;
        }
    }

    pub(crate) 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)
    }

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

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

    pub(crate) 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)
    }

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

    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)))
    }

    pub(crate) 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)
    }
}

// ── PackedBitMatrix ───────────────────────────────────────────────────────────

const PBMX_MAGIC:  [u8; 4] = *b"PBMX";
const PBMX_HEADER: usize   = 24; // magic(4) + pad(4) + n_rows(8) + n_cols(8)
const PBIV_HEADER: usize   = 16; // magic(4) + pad(4) + n(8)

/// Single-file packed layout: all columns concatenated behind a header.
pub struct PackedBitMatrix {
    mmap:         Mmap,
    n_rows:       usize,
    n_cols:       usize,
    /// Absolute byte offset to the start of each column's bit data
    /// (= file offset of the PBIV blob + PBIV_HEADER).
    data_offsets: Vec<usize>,
}

impl PackedBitMatrix {
    pub(crate) fn open(path: &Path) -> io::Result<Self> {
        let mmap = unsafe { Mmap::map(&File::open(path)?)? };
        if mmap.len() < PBMX_HEADER {
            return Err(io::Error::new(io::ErrorKind::InvalidData, "PBMX file too short"));
        }
        if &mmap[0..4] != &PBMX_MAGIC {
            return Err(io::Error::new(io::ErrorKind::InvalidData, "bad PBMX magic"));
        }
        let n_rows = u64::from_le_bytes(mmap[8..16].try_into().unwrap())  as usize;
        let n_cols = u64::from_le_bytes(mmap[16..24].try_into().unwrap()) as usize;

        let mut data_offsets = Vec::with_capacity(n_cols);
        for c in 0..n_cols {
            let off_pos = PBMX_HEADER + c * 8;
            let col_file_off = u64::from_le_bytes(mmap[off_pos..off_pos+8].try_into().unwrap()) as usize;
            data_offsets.push(col_file_off + PBIV_HEADER);
        }

        Ok(Self { mmap, n_rows, n_cols, data_offsets })
    }

    #[inline]
    pub(crate) fn fill_row(&self, slot: usize, buf: &mut [u32]) {
        for (c, &data_off) in self.data_offsets.iter().enumerate() {
            buf[c] = ((self.mmap[data_off + (slot >> 3)] >> (slot & 7)) & 1) as u32;
        }
    }

    pub(crate) fn row(&self, slot: usize) -> Box<[bool]> {
        (0..self.n_cols).map(|c| {
            (self.mmap[self.data_offsets[c] + (slot >> 3)] >> (slot & 7)) & 1 != 0
        }).collect()
    }
}

/// Build `presence/matrix.pbmx` from existing `col_*.pbiv` files.
pub fn pack_bit_matrix(dir: &Path) -> io::Result<()> {
    let meta = MatrixMeta::load(dir)?;
    let n_cols = meta.n_cols;

    let col_files: Vec<Vec<u8>> = (0..n_cols)
        .map(|c| fs::read(col_path(dir, c)))
        .collect::<io::Result<_>>()?;

    let header_size = PBMX_HEADER + n_cols * 8;
    let mut col_offset = header_size;
    let mut offsets = Vec::with_capacity(n_cols);
    for data in &col_files {
        offsets.push(col_offset as u64);
        col_offset += data.len();
    }

    let packed_path = dir.join("matrix.pbmx");
    let mut file = File::create(&packed_path)?;
    file.write_all(&PBMX_MAGIC)?;
    file.write_all(&[0u8; 4])?;
    file.write_all(&(meta.n as u64).to_le_bytes())?;
    file.write_all(&(n_cols as u64).to_le_bytes())?;
    for &off in &offsets { file.write_all(&off.to_le_bytes())?; }
    for data in &col_files { file.write_all(data)?; }
    drop(file);

    for c in 0..n_cols { fs::remove_file(col_path(dir, c))?; }
    fs::remove_file(dir.join("meta.json"))?;
    Ok(())
}

// ── PersistentBitMatrix — public enum ────────────────────────────────────────

/// Bit matrix that transparently handles columnar, packed, and implicit formats.
///
/// - `Columnar`: per-column `.pbiv` files (original format, used during build)
/// - `Packed`:   single `matrix.pbmx` file (optimised for query — one `mmap`)
/// - `Implicit`: no file — all values are 1 (mono-genome presence/absence)
pub enum PersistentBitMatrix {
    Columnar(ColumnarBitMatrix),
    Packed(PackedBitMatrix),
    Implicit { n_rows: usize, n_cols: usize },
}

impl PersistentBitMatrix {
    /// Open from `layer_dir`, auto-detecting the format.
    ///
    /// Checks (in order):
    /// 1. `layer_dir/presence/matrix.pbmx`  → Packed
    /// 2. `layer_dir/presence/meta.json`    → Columnar
    /// 3. `layer_dir/layer_meta.json`        → Implicit (new index)
    /// 4. `layer_dir/unitigs.bin`            → Implicit with warning (old index)
    pub fn open(layer_dir: &Path) -> io::Result<Self> {
        let presence_dir = layer_dir.join("presence");

        if presence_dir.join("matrix.pbmx").exists() {
            return Ok(Self::Packed(PackedBitMatrix::open(&presence_dir.join("matrix.pbmx"))?));
        }

        if MatrixMeta::load(&presence_dir).is_ok() {
            return Ok(Self::Columnar(ColumnarBitMatrix::open(&presence_dir)?));
        }

        // No presence matrix → Implicit; requires layer_meta.json
        let meta = LayerMeta::load(layer_dir).map_err(|_| io::Error::new(
            io::ErrorKind::NotFound,
            format!(
                "no presence matrix and no layer_meta.json in {} — run 'obikmer upgrade'",
                layer_dir.display()
            ),
        ))?;
        Ok(Self::Implicit { n_rows: meta.n, n_cols: 1 })
    }

    pub fn n(&self) -> usize {
        match self {
            Self::Columnar(m)            => m.n(),
            Self::Packed(m)              => m.n_rows,
            Self::Implicit { n_rows, .. } => *n_rows,
        }
    }

    pub fn n_cols(&self) -> usize {
        match self {
            Self::Columnar(m)            => m.n_cols(),
            Self::Packed(m)              => m.n_cols,
            Self::Implicit { n_cols, .. } => *n_cols,
        }
    }

    pub fn col(&self, c: usize) -> &PersistentBitVec {
        match self {
            Self::Columnar(m) => m.col(c),
            _ => panic!("col() only available on Columnar PersistentBitMatrix"),
        }
    }

    pub fn row(&self, slot: usize) -> Box<[bool]> {
        match self {
            Self::Columnar(m)             => m.row(slot),
            Self::Packed(m)               => m.row(slot),
            Self::Implicit { n_cols, .. } => vec![true; *n_cols].into_boxed_slice(),
        }
    }

    /// Fill `buf[i]` with `col_i[slot]` as 0/1 u32, without allocating.
    pub fn fill_row(&self, slot: usize, buf: &mut [u32]) {
        match self {
            Self::Columnar(m)             => m.fill_row(slot, buf),
            Self::Packed(m)               => m.fill_row(slot, buf),
            Self::Implicit { n_cols, .. } => buf[..*n_cols].fill(1),
        }
    }

    pub fn count_ones(&self) -> Array1<u64> {
        match self {
            Self::Columnar(m) => m.count_ones(),
            _ => panic!("count_ones() only available on Columnar PersistentBitMatrix"),
        }
    }

    pub fn jaccard_dist_matrix(&self) -> Array2<f64> {
        match self {
            Self::Columnar(m) => m.jaccard_dist_matrix(),
            _ => panic!("jaccard_dist_matrix() only available on Columnar PersistentBitMatrix"),
        }
    }

    pub fn hamming_dist_matrix(&self) -> Array2<u64> {
        match self {
            Self::Columnar(m) => m.hamming_dist_matrix(),
            _ => panic!("hamming_dist_matrix() only available on Columnar PersistentBitMatrix"),
        }
    }

    pub fn partial_jaccard_dist_matrix(&self) -> (Array2<u64>, Array2<u64>) {
        match self {
            Self::Columnar(m) => m.partial_jaccard_dist_matrix(),
            _ => panic!("partial_jaccard_dist_matrix() only available on Columnar PersistentBitMatrix"),
        }
    }

    pub fn partial_hamming_dist_matrix(&self) -> Array2<u64> {
        match self {
            Self::Columnar(m) => m.partial_hamming_dist_matrix(),
            _ => panic!("partial_hamming_dist_matrix() only available on Columnar PersistentBitMatrix"),
        }
    }

    /// Append a new column to an on-disk Columnar matrix.
    pub fn append_column(dir: &Path, value_of: impl Fn(usize) -> bool) -> io::Result<()> {
        ColumnarBitMatrix::append_column(dir, value_of)
    }
}

// ── 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 (unchanged — always builds Columnar) ──────────────────────────────

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)
    }
}

// ── Helpers ───────────────────────────────────────────────────────────────────

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
}
