use crate::formulas::{EncodedFormula, FormulaFactory};
use regex::Regex;
use std::fs::File;
use std::io;
use std::io::{BufRead, BufReader};
pub fn read_cnf(file_path: &str, f: &FormulaFactory) -> io::Result<Vec<EncodedFormula>> {
read_cnf_with_prefix(file_path, f, "v")
}
pub fn read_cnf_with_prefix(file_path: &str, f: &FormulaFactory, prefix: &str) -> io::Result<Vec<EncodedFormula>> {
let mut result = Vec::new();
let file = File::open(file_path)?;
let reader = BufReader::new(file);
for l in reader.lines() {
let line = l?;
if !line.starts_with('c') && !line.starts_with('p') && !line.trim().is_empty() {
let split: Vec<&str> = Regex::new(r"[ \t]+").unwrap().split(&line).collect();
assert_eq!(*split.last().unwrap(), "0", "Line {line} did not end with 0.");
let vars = split
.iter()
.take(split.len() - 1)
.map(|&lit| lit.trim())
.filter(|&lit| !lit.is_empty())
.map(|lit| {
lit.strip_prefix('-')
.map_or_else(|| f.variable(&format!("{prefix}{lit}")), |stripped| f.literal(&format!("{prefix}{stripped}"), false))
})
.collect::<Box<[_]>>();
result.push(f.or(&vars));
}
}
Ok(result)
}