silcrow 0.2.0

Deterministic CLI for a citable, checkable graph of laws in a git tree.
use anyhow::Result;
use crossterm::terminal;
use std::io::{self, IsTerminal, Write};
use std::path::Path;
use std::process::{Command, Stdio};

use crate::parse::Law;

const MIN_WIDTH: usize = 40;
const MAX_WIDTH: usize = 100;

pub fn is_tty_stdout() -> bool {
    io::stdout().is_terminal()
}

pub fn term_width() -> usize {
    usable_cols(terminal::size().ok().map(|(w, _)| w as usize))
}

fn usable_cols(reported: Option<usize>) -> usize {
    reported
        .or_else(|| {
            std::env::var("COLUMNS")
                .ok()
                .and_then(|s| s.parse().ok())
                .filter(|&cols| cols > 0)
        })
        .unwrap_or(72)
        .clamp(MIN_WIDTH, MAX_WIDTH)
        .saturating_sub(1)
}

pub fn page(text: &str) -> Result<()> {
    // § kf718b2g7.a@s2tf1
    if !should_page(text) {
        print!("{text}");
        return Ok(());
    }
    let spec = std::env::var("PAGER")
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty() && s != "cat");
    let mut cmd = match spec.as_deref() {
        Some(spec) => {
            let mut parts = spec.split_whitespace();
            let bin = parts.next().unwrap_or("less");
            let mut cmd = Command::new(bin);
            for arg in parts {
                cmd.arg(arg);
            }
            cmd
        }
        None => {
            let mut cmd = Command::new("less");
            cmd.args(["-F", "-X"]);
            cmd
        }
    };
    cmd.stdin(Stdio::piped());
    match cmd.spawn() {
        Ok(mut child) => {
            if let Some(mut stdin) = child.stdin.take() {
                stdin.write_all(text.as_bytes())?;
            }
            let _ = child.wait();
            Ok(())
        }
        Err(_) => {
            print!("{text}");
            Ok(())
        }
    }
}

fn should_page(text: &str) -> bool {
    let rows = terminal::size()
        .ok()
        .map(|(_, height)| height as usize)
        .unwrap_or(24);
    pages(
        text,
        is_tty_stdout(),
        std::env::var("PAGER").ok().as_deref(),
        rows,
    )
}

fn pages(text: &str, tty: bool, pager: Option<&str>, rows: usize) -> bool {
    if !tty || pager.is_some_and(|pager| pager.trim() == "cat") {
        return false;
    }
    text.lines().count() >= rows
}

pub fn compact_string(groups: &[(std::path::PathBuf, Vec<&Law>)], width: usize) -> Result<String> {
    // § kf718b2g7@z6jst
    let mut buf = Vec::new();
    for line in &layout(groups, width) {
        writeln!(buf, "{}", line_plain(line))?;
    }
    Ok(String::from_utf8(buf)?)
}

#[derive(Debug, Clone)]
enum Line {
    Chrome(String),
    File(String),
    Blank,
    Id(String),
    Body(String),
}

fn layout(groups: &[(std::path::PathBuf, Vec<&Law>)], width: usize) -> Vec<Line> {
    let total: usize = groups.iter().map(|(_, arts)| arts.len()).sum();
    let mut lines = vec![Line::Chrome(truncate(&chrome(total), width))];
    for (path, arts) in groups {
        lines.push(Line::Blank);
        lines.push(Line::File(truncate(&file_label(path), width)));
        for art in arts {
            lines.push(Line::Id(format!("  {} {}", crate::list::sign(art), art.id)));
            let body = truncate(&display_text(&art.name), width.saturating_sub(2).max(1));
            lines.push(Line::Body(format!("  {body}")));
            for (letter, text, draft) in crate::list::live_clauses(art) {
                let head = format!("    ({letter}){} ", crate::list::mark(draft));
                let cols = width.saturating_sub(head.chars().count()).max(1);
                let text = truncate(&display_text(text), cols);
                lines.push(Line::Body(format!("{head}{text}")));
            }
        }
    }
    lines
}

fn chrome(total: usize) -> String {
    format!("Laws  {total}")
}

fn line_plain(line: &Line) -> String {
    match line {
        Line::Blank => String::new(),
        Line::Chrome(text) | Line::File(text) | Line::Body(text) | Line::Id(text) => text.clone(),
    }
}

pub fn file_label(path: &Path) -> String {
    path.file_stem()
        .and_then(|s| s.to_str())
        .map(str::to_string)
        .unwrap_or_else(|| path.display().to_string())
}

pub fn display_text(s: &str) -> String {
    s.replace("**", "")
        .replace('`', "")
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
}

fn truncate(s: &str, cols: usize) -> String {
    if cols == 0 {
        return String::new();
    }
    let chars: Vec<char> = s.chars().collect();
    if chars.len() <= cols {
        return s.to_string();
    }
    if cols == 1 {
        return "…".to_string();
    }
    let mut out: String = chars.into_iter().take(cols - 1).collect();
    while out.ends_with(' ') {
        out.pop();
    }
    out.push('…');
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{Law, Location};
    use std::path::PathBuf;

    fn law_fix(id: &str, name: &str) -> Law {
        Law {
            draft: false,
            body: String::new(),
            end: 1,
            context: String::new(),
            aliases: Vec::new(),
            id: id.to_string(),
            name: name.to_string(),
            loc: Location {
                path: PathBuf::from("docs/decisions/cli.md"),
                line: 1,
            },
            clauses: Vec::new(),
            struck: false,
            public: false,
        }
    }

    #[test]
    fn law_is_two_left_aligned_lines() {
        let a = law_fix(
            "r2m7q4x8z",
            "The framework ships as one skill that routes between drafting and verification.",
        );
        let groups = vec![(a.loc.path.clone(), vec![&a])];
        let text = compact_string(&groups, 56).unwrap();
        let id_line = text.lines().find(|l| l.contains('§')).unwrap();
        let sentence = text.lines().find(|l| l.contains("The framework")).unwrap();
        assert!(id_line.contains("§ r2m7q4x8z"));
        assert!(!id_line.contains("The framework"));
        assert!(sentence.starts_with("  The framework"));
        assert!(sentence.chars().count() <= 56);
    }

    #[test]
    fn long_sentence_truncates_on_one_line() {
        let a = law_fix(
            "b8yk2z0vw",
            "The citation graph must not depend on where files live: renaming a policy file or moving a directory must not break a citation or an implementation.",
        );
        let groups = vec![(a.loc.path.clone(), vec![&a])];
        let text = compact_string(&groups, 48).unwrap();
        let sentence = text
            .lines()
            .find(|l| l.contains("citation") || l.contains("The citation"))
            .unwrap();
        assert!(sentence.ends_with('…'), "{sentence}");
        assert!(sentence.chars().count() <= 48, "{sentence}");
        assert!(!sentence.contains("             "));
    }

    #[test]
    fn strips_markdown_for_display() {
        let a = law_fix(
            "p3xv0c2ng",
            "A law is a **binding** sentence: one `§` marker.",
        );
        let groups = vec![(a.loc.path.clone(), vec![&a])];
        let text = compact_string(&groups, 80).unwrap();
        assert!(!text.contains("**"));
        assert!(!text.contains('`'));
        assert!(text.contains("binding"));
    }

    #[test]
    fn a_text_that_fits_the_rows_or_a_cat_pager_is_not_paged() {
        let text = "line\n".repeat(23);
        assert!(!pages(&text, true, None, 24));
        assert!(pages(&"line\n".repeat(24), true, None, 24));
        assert!(pages(&"line\n".repeat(24), true, Some("less -R"), 24));
        assert!(!pages(&"line\n".repeat(100), true, Some(" cat "), 24));
        assert!(!pages(&"line\n".repeat(100), false, None, 24));
    }

    #[test]
    fn usable_cols_never_fills_the_row() {
        assert_eq!(usable_cols(Some(80)), 79);
        assert_eq!(usable_cols(Some(10)), 39);
    }
}