use crate::{Store, StoreError, new_id, now_ms};
use griz_core::{
ChangeKind, Confidence, Edit, FileChange, MapSource, Op, Plan, Problem, build_plan,
};
use rusqlite::params;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeMap, BTreeSet},
path::{Path, PathBuf},
};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct FileRecord {
pub path: PathBuf,
pub kind: ChangeKind,
pub before_hash: Option<String>,
pub after_hash: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct PlanRecord {
pub id: String,
pub purpose: String,
pub selected_from: Option<String>,
pub ops: Vec<Op>,
pub edits: Vec<Edit>,
pub problems: Vec<Problem>,
pub files: Vec<FileRecord>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub unchanged_inputs: BTreeMap<PathBuf, Option<String>>,
pub confidence: Confidence,
pub created_at: i64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Selection {
#[serde(default)]
pub paths: Vec<PathBuf>,
#[serde(default)]
pub edits: Vec<String>,
pub min_confidence: Option<Confidence>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub resolved_only: bool,
}
impl Store {
pub fn save_plan(
&self,
purpose: &str,
ops: Vec<Op>,
plan: Plan,
) -> Result<PlanRecord, StoreError> {
self.store_plan(purpose, ops, plan, None)
}
fn store_plan(
&self,
purpose: &str,
ops: Vec<Op>,
plan: Plan,
selected_from: Option<String>,
) -> Result<PlanRecord, StoreError> {
self.persist_plan_blobs(&plan)?;
let files = plan.files.iter().map(file_record).collect();
let confidence = plan.confidence();
let unchanged_inputs = plan
.unchanged_inputs
.into_iter()
.map(|(path, text)| (path, text.as_deref().map(griz_core::content_hash)))
.collect();
let record = PlanRecord {
id: new_id("plan"),
purpose: purpose.to_string(),
selected_from,
confidence,
ops,
edits: plan.edits,
problems: plan.problems,
files,
unchanged_inputs,
created_at: now_ms(),
};
self.insert_plan(&record)?;
Ok(record)
}
fn insert_plan(&self, record: &PlanRecord) -> Result<(), StoreError> {
let body = serde_json::to_string(record)?;
self.with(|conn| {
conn.execute(
"INSERT INTO plans (id, created_at, body) VALUES (?1, ?2, ?3)",
params![record.id, record.created_at, body],
)?;
Ok(())
})
}
pub fn plan(&self, id: &str) -> Result<PlanRecord, StoreError> {
let sql = "SELECT body FROM plans WHERE id = ?1";
let body = self.with(|conn| crate::body_by_id(conn, sql, id))?;
let body = body.ok_or_else(|| StoreError::NotFound(format!("plan {id}")))?;
Ok(serde_json::from_str(&body)?)
}
pub fn plan_changes(&self, record: &PlanRecord) -> Result<Vec<FileChange>, StoreError> {
record
.files
.iter()
.map(|file| {
Ok(FileChange {
path: file.path.clone(),
kind: file.kind,
before: self.text(file.before_hash.as_deref())?,
before_hash: file.before_hash.clone(),
after: self.text(file.after_hash.as_deref())?,
after_hash: file.after_hash.clone(),
})
})
.collect()
}
fn plan_source(&self, record: &PlanRecord, ops: &[Op]) -> Result<MapSource, StoreError> {
let needed = (ops.len() != record.ops.len()).then(|| input_paths(ops));
let mut files = record
.unchanged_inputs
.iter()
.filter(|(path, _)| {
needed
.as_ref()
.is_none_or(|paths| paths.contains(path.as_path()))
})
.map(|(path, hash)| Ok((path.clone(), self.text(hash.as_deref())?)))
.collect::<Result<BTreeMap<_, _>, StoreError>>()?;
for file in record.files.iter().filter(|file| {
needed
.as_ref()
.is_none_or(|paths| paths.contains(file.path.as_path()))
}) {
files.insert(file.path.clone(), self.text(file.before_hash.as_deref())?);
}
Ok(MapSource::new(files))
}
fn text(&self, hash: Option<&str>) -> Result<Option<String>, StoreError> {
hash.map(|hash| self.get_blob(hash)).transpose()
}
pub fn select(
&self,
id: &str,
selection: &Selection,
purpose: &str,
) -> Result<PlanRecord, StoreError> {
let original = self.plan(id)?;
let ops = selected_ops(&original, selection);
let source = self.plan_source(&original, &ops)?;
let plan = build_plan(&ops, &source);
self.store_plan(purpose, ops, plan, Some(original.id))
}
}
fn input_paths(ops: &[Op]) -> BTreeSet<&Path> {
let mut paths = BTreeSet::new();
for op in ops {
paths.insert(op.path().as_path());
if let Op::Move { to, .. } = op {
paths.insert(to.as_path());
}
}
paths
}
struct Kept {
by_path: bool,
by_edit: bool,
by_confidence: bool,
}
fn selected_ops(plan: &PlanRecord, selection: &Selection) -> Vec<Op> {
let paths: BTreeSet<&Path> = selection.paths.iter().map(PathBuf::as_path).collect();
let edits: BTreeSet<&str> = selection.edits.iter().map(String::as_str).collect();
let mut kept: Vec<_> = plan
.ops
.iter()
.map(|op| Kept {
by_path: paths.is_empty() || paths.contains(op.path().as_path()),
by_edit: edits.is_empty() && !selection.resolved_only,
by_confidence: true,
})
.collect();
for edit in &plan.edits {
let trusted = selection
.min_confidence
.is_none_or(|min| edit.confidence >= min);
let Some(kept) = kept.get_mut(edit.op) else {
continue;
};
kept.by_path |= paths.contains(edit.path.as_path());
kept.by_edit |=
edits.contains(edit.id.as_str()) || (selection.resolved_only && edits.is_empty());
kept.by_confidence &= trusted;
}
plan.ops
.iter()
.zip(kept)
.filter(|(_, kept)| kept.by_path && kept.by_edit && kept.by_confidence)
.map(|(op, _)| op.clone())
.collect()
}
fn file_record(file: &FileChange) -> FileRecord {
FileRecord {
path: file.path.clone(),
kind: file.kind,
before_hash: file.before_hash.clone(),
after_hash: file.after_hash.clone(),
}
}