rekon 0.0.2

Reconstruct where your time and compute went: account for agentic work on two axes and review a daily ledger instead of keeping a timesheet.
//! Command handlers and the glue between config, connectors, and the core pipeline.

use std::io;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use chrono::{Local, NaiveDate};
use tracing::info;

use rekon_core::config::Config;
use rekon_core::model::LedgerStatus;
use rekon_core::report::{Emitter, JsonEmitter, TextEmitter};
use rekon_core::store::{Store, open_store};

use crate::cli::{Cli, Command, Format};

/// Dispatch a parsed command.
pub fn run(cli: Cli) -> Result<()> {
    let config_path = cli.config.unwrap_or_else(default_config_path);
    match cli.command {
        Command::Init { force } => cmd_init(&config_path, force),
        Command::Reconstruct { date, repos, force } => {
            let cfg = load_config(&config_path)?;
            cmd_reconstruct(&cfg, date, &repos, force)
        }
        Command::Review { date, format, edit } => {
            let cfg = load_config(&config_path)?;
            cmd_review(&cfg, date, format, edit)
        }
        Command::Approve { date } => {
            let cfg = load_config(&config_path)?;
            cmd_approve(&cfg, date)
        }
        Command::Config => cmd_config(&config_path),
    }
}

fn cmd_init(path: &Path, force: bool) -> Result<()> {
    if path.exists() && !force {
        bail!(
            "{} already exists; pass --force to overwrite",
            path.display()
        );
    }
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(path, Config::default().to_toml()?)?;
    println!("wrote {}", path.display());
    Ok(())
}

fn cmd_reconstruct(
    cfg: &Config,
    date: Option<NaiveDate>,
    repos: &[PathBuf],
    force: bool,
) -> Result<()> {
    let date = date.unwrap_or_else(today);
    let store = open_store(&cfg.store)?;

    // Don't discard an approved day by rebuilding over it. The server enforces the
    // same invariant (it returns 409); --force is the escape hatch.
    if !force
        && let Ok(existing) = store.load_ledger(date)
        && existing.status == LedgerStatus::Approved
    {
        bail!("{date} is approved; pass --force to rebuild and discard the approval");
    }

    let (ledger, events) = rekon_connectors::reconstruct_day(cfg, date, repos)?;
    store.save_events(date, &events)?;
    store.save_ledger(&ledger)?;

    let mut out = io::stdout().lock();
    TextEmitter.emit(&ledger, &mut out)?;
    Ok(())
}

fn cmd_review(cfg: &Config, date: Option<NaiveDate>, format: Format, edit: bool) -> Result<()> {
    let date = date.unwrap_or_else(today);
    let store = open_store(&cfg.store)?;
    let ledger = store.load_ledger(date).with_context(|| {
        format!("no ledger for {date}; run `rekon reconstruct --date {date}` first")
    })?;
    if edit {
        return review_edit(&*store, ledger);
    }
    let mut out = io::stdout().lock();
    match format {
        Format::Text => TextEmitter.emit(&ledger, &mut out)?,
        Format::Json => JsonEmitter { pretty: true }.emit(&ledger, &mut out)?,
    }
    Ok(())
}

// Write the draft to a temp file, open it in the editor, then apply the edits and
// approve. On any error the stored draft is left untouched.
fn review_edit(store: &dyn Store, ledger: rekon_core::Ledger) -> Result<()> {
    let path = std::env::temp_dir().join(format!("rekon-{}.toml", ledger.date));
    std::fs::write(&path, rekon_core::review::to_editable_toml(&ledger))?;

    launch_editor(&path)?;

    let edited = std::fs::read_to_string(&path)?;
    let updated =
        rekon_core::review::apply_edits(&ledger, &edited).context("applying your edits")?;
    store.save_ledger(&updated)?;
    let _ = std::fs::remove_file(&path);

    let mut out = io::stdout().lock();
    TextEmitter.emit(&updated, &mut out)?;
    eprintln!("approved {}", updated.date);
    Ok(())
}

fn launch_editor(path: &Path) -> Result<()> {
    let editor = std::env::var("VISUAL")
        .or_else(|_| std::env::var("EDITOR"))
        .unwrap_or_else(|_| "vi".to_string());
    // Split so "$EDITOR" values like "code --wait" work; the file is the last arg.
    let mut parts = editor.split_whitespace();
    let program = parts.next().unwrap_or("vi");
    let mut command = std::process::Command::new(program);
    for arg in parts {
        command.arg(arg);
    }
    command.arg(path);
    let status = command
        .status()
        .with_context(|| format!("launching editor `{editor}`"))?;
    if !status.success() {
        anyhow::bail!("editor exited with a non-zero status; the day was not changed");
    }
    Ok(())
}

fn cmd_approve(cfg: &Config, date: Option<NaiveDate>) -> Result<()> {
    let date = date.unwrap_or_else(today);
    let store = open_store(&cfg.store)?;
    let mut ledger = store
        .load_ledger(date)
        .with_context(|| format!("no ledger for {date}"))?;
    ledger.status = LedgerStatus::Approved;
    store.save_ledger(&ledger)?;
    println!("approved {date}");
    Ok(())
}

fn cmd_config(path: &Path) -> Result<()> {
    println!("config: {}", path.display());
    let cfg = load_config(path)?;
    println!("store:  {}", cfg.store.dir.display());
    Ok(())
}

fn load_config(path: &Path) -> Result<Config> {
    if path.exists() {
        Config::load(path).with_context(|| format!("loading config {}", path.display()))
    } else {
        info!(path = %path.display(), "no config file; using defaults");
        Ok(Config::default())
    }
}

fn today() -> NaiveDate {
    Local::now().date_naive()
}

fn default_config_path() -> PathBuf {
    match std::env::var_os("HOME") {
        Some(home) => PathBuf::from(home).join(".config/rekon/rekon.toml"),
        None => PathBuf::from("rekon.toml"),
    }
}