use std::path::Path;

use anyhow::Result;

use astmap_core::diff::{
    diff_working_tree, resolve_digest_reference, since_against_ref, update_session_anchor,
    DigestResult,
};
use astmap_core::scanner::scan;

use super::VcsContext;

pub fn digest(project_dir: &Path, depth: i64, ctx: &VcsContext<'_>) -> Result<DigestResult> {
    let ext = ctx.lang.supported_extensions();
    // Ensure index is fresh before comparing
    if let Err(e) = scan(project_dir, ctx.scan_store, false, ctx.lang, ctx.discovery) {
        tracing::warn!(
            "auto-scan failed, proceeding with potentially stale index: {}",
            e
        );
    }
    let reference = resolve_digest_reference(ctx.vcs, ctx.diff_store)?;
    let since_result =
        since_against_ref(ctx.vcs, &reference, ctx.diff_store, depth, ext, ctx.lang)?;
    let uncommitted = diff_working_tree(ctx.vcs, ctx.diff_store, depth, ext).ok();
    update_session_anchor(ctx.vcs, ctx.diff_store)?;
    Ok(DigestResult {
        since: since_result,
        uncommitted,
    })
}
