use std::path::{Path, PathBuf};
use assay_core::agentic::{build_suggestions, AgenticCtx, SuggestedPatch};
use assay_core::config::{load_config_with_cause, path_resolver::PathResolver, LoadOptions};
use assay_core::errors::diagnostic::{codes, Diagnostic};
use crate::cli::args::DoctorArgs;
use crate::cli::helpers::{decide_exit, decide_repair_failure_exit, normalize_severity};
use crate::cli::interaction::confirm;
use super::implementation::config_failure;
use super::patching::{apply_patch_to_file, create_empty_trace, preview_patch};
#[cfg(test)]
mod tests;
fn is_missing_trace(diagnostic: &Diagnostic) -> bool {
diagnostic.code == codes::E_TRACE_MISS || diagnostic.code == codes::E_PATH_NOT_FOUND
}
#[derive(Debug, Clone)]
enum DoctorFixOp {
Patch(SuggestedPatch),
CreateTrace { path: PathBuf },
}
impl DoctorFixOp {
fn id(&self) -> String {
match self {
DoctorFixOp::Patch(p) => p.id.clone(),
DoctorFixOp::CreateTrace { path } => format!("create_trace:{}", path.display()),
}
}
fn title(&self) -> String {
match self {
DoctorFixOp::Patch(p) => p.title.clone(),
DoctorFixOp::CreateTrace { path } => {
format!("Create missing trace file '{}'.", path.display())
}
}
}
}
pub(super) async fn run_doctor_fix(
args: &DoctorArgs,
config_path: &Path,
diagnostics: &[Diagnostic],
legacy_mode: bool,
) -> anyhow::Result<i32> {
let unfixed_exit = decide_exit(diagnostics);
let (_actions, mut patches) = build_suggestions(
diagnostics,
&AgenticCtx {
policy_path: None,
config_path: Some(config_path.to_path_buf()),
},
);
patches.sort_by(|a, b| a.id.cmp(&b.id));
let mut ops: Vec<DoctorFixOp> = patches.into_iter().map(DoctorFixOp::Patch).collect();
if diagnostics.iter().any(is_missing_trace) {
if let Some(trace_path) = trace_fix_target(args, diagnostics) {
if !trace_path.exists() {
ops.push(DoctorFixOp::CreateTrace { path: trace_path });
}
}
}
ops.sort_by_key(|op| op.id());
if ops.is_empty() {
println!("\nNo auto-fixable diagnostics found.");
return Ok(unfixed_exit);
}
println!("\nAuto-fix candidates:");
for op in &ops {
println!(" - {}", op.title());
}
let mut applied = 0usize;
let mut failed = 0usize;
for op in &ops {
let should_apply = confirm(
&format!("Apply fix '{}'?", op.title()),
args.yes || args.dry_run,
)?;
if !should_apply {
continue;
}
match op {
DoctorFixOp::Patch(patch) => {
if args.dry_run {
preview_patch(patch)?;
applied += 1;
continue;
}
match apply_patch_to_file(patch) {
Ok(_) => {
eprintln!("Applied: {}", patch.id);
applied += 1;
}
Err(err) => {
eprintln!("Failed: {} ({})", patch.id, err);
failed += 1;
}
}
}
DoctorFixOp::CreateTrace { path } => {
if args.dry_run {
println!("[dry-run] would create trace file: {}", path.display());
applied += 1;
continue;
}
match create_empty_trace(path) {
Ok(_) => {
eprintln!("Applied: created trace file {}", path.display());
applied += 1;
}
Err(err) => {
eprintln!("Failed: could not create {} ({})", path.display(), err);
failed += 1;
}
}
}
}
}
if failed > 0 {
return Ok(decide_repair_failure_exit());
}
if applied == 0 {
println!("No fixes applied.");
return Ok(unfixed_exit);
}
if args.dry_run {
println!("\nDry run complete. {} fix(es) previewed.", applied);
return Ok(unfixed_exit);
}
let cfg = match load_config_with_cause(
config_path,
LoadOptions {
legacy_mode,
..Default::default()
},
) {
Ok(c) => c,
Err(err) => {
eprintln!("Re-validation skipped: config still invalid ({})", err);
return Ok(config_failure(config_path, &err).exit_code);
}
};
let resolver = PathResolver::new(config_path);
let opts = assay_core::doctor::DoctorOptions {
config_path: config_path.to_path_buf(),
trace_file: args.trace_file.clone(),
baseline_file: args.baseline.clone(),
db_path: args.db.clone(),
replay_strict: args.replay_strict,
};
let report = assay_core::doctor::doctor(&cfg, &opts, &resolver).await?;
let remaining_errors = report
.diagnostics
.iter()
.filter(|d| normalize_severity(&d.severity) == "error")
.count();
println!(
"\nApplied {} fix(es). Remaining: {} error(s).",
applied, remaining_errors
);
Ok(decide_exit(&report.diagnostics))
}
fn trace_fix_target(args: &DoctorArgs, diagnostics: &[Diagnostic]) -> Option<PathBuf> {
if let Some(p) = &args.trace_file {
return Some(p.clone());
}
for d in diagnostics {
if !is_missing_trace(d) {
continue;
}
if let Some(path) = d.context.get("trace_file").and_then(|v| v.as_str()) {
if !path.trim().is_empty() {
return Some(PathBuf::from(path));
}
}
if let Some(path) = d.context.get("path").and_then(|v| v.as_str()) {
if !path.trim().is_empty() {
return Some(PathBuf::from(path));
}
}
}
None
}