silcrow 0.2.1

Deterministic CLI for a citable, checkable graph of laws in a git tree.
use std::collections::{HashMap, HashSet};

use crate::model::{Scan, Target};

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DisplayKey {
    pub name: String,
    pub note: String,
    pub section: u32,
    pub clause: Option<String>,
}

#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct Node {
    pub name: String,
    pub id: String,
    pub letter: Option<String>,
    pub struck: bool,
    /// A draft law, or a clause of one or written `(x)?`: it owes no marker.
    pub draft: bool,
    /// A law written `§!`, or a clause of one.
    pub public: bool,
    pub path: String,
    pub line: usize,
}

#[derive(Debug, Default)]
pub struct Graph {
    pub by_id: HashMap<String, Node>,
    pub by_display: HashMap<DisplayKey, String>,
    pub law_ids: HashMap<String, Vec<String>>,
    pub retired: HashSet<String>,
    /// Each alias anchor a head keeps, to the id the law carries now.
    pub aliases: HashMap<String, String>,
}

impl Graph {
    pub fn from_scan(scan: &Scan) -> Self {
        // § h36xkjqaa.a@g42x3
        let mut graph = Graph::default();
        for law in &scan.laws {
            // § zrj8yeg6g.b@7ym2v
            if law.struck {
                graph.retired.insert(law.id.clone());
            }
            // § end zrj8yeg6g.b
            for alias in &law.aliases {
                graph.aliases.insert(alias.clone(), law.id.clone());
            }
            graph
                .law_ids
                .entry(law.name.clone())
                .or_default()
                .push(law.id.clone());
            // § one pxmeee9ra.d@6w5s2
            graph.by_id.insert(
                law.id.clone(),
                Node {
                    name: law.name.clone(),
                    id: law.id.clone(),
                    letter: None,
                    struck: law.struck,
                    draft: law.draft,
                    public: law.public,
                    path: law.loc.path.display().to_string(),
                    line: law.loc.line,
                },
            );
            for al in &law.clauses {
                let Some(letter) = &al.letter else {
                    continue;
                };
                let key = format!("{}.{}", law.id, letter);
                graph.by_id.insert(
                    key,
                    Node {
                        name: law.name.clone(),
                        id: law.id.clone(),
                        letter: Some(letter.clone()),
                        struck: al.struck,
                        draft: al.draft,
                        public: law.public,
                        path: al.loc.path.display().to_string(),
                        line: al.loc.line,
                    },
                );
            }
        }
        graph
    }

    pub fn lookup(&self, name: &str, target: &Target) -> Option<&Node> {
        self.lookup_target(name, target)
    }

    pub fn lookup_target(&self, name: &str, target: &Target) -> Option<&Node> {
        let key = match target {
            Target::Stable {
                id,
                letter: Some(letter),
            } => format!("{id}.{letter}"),
            Target::Stable { id, letter: None } => id.clone(),
            Target::Display { clause, .. } => clause
                .as_ref()
                .and_then(|al| self.lookup_display(name, al))?,
        };
        self.by_id.get(&key)
    }

    fn lookup_display(&self, name: &str, clause: &str) -> Option<String> {
        let key = DisplayKey {
            name: name.to_string(),
            note: String::new(),
            section: 0,
            clause: Some(clause.to_string()),
        };
        self.by_display.get(&key).cloned()
    }

    pub fn is_live(&self, node: &Node) -> bool {
        if node.struck || self.retired.contains(&node.id) {
            return false;
        }
        if let Some(letter) = &node.letter {
            let clause_key = format!("{}.{}", node.id, letter);
            if self.retired.contains(&clause_key) {
                return false;
            }
        }
        true
    }
}

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

    fn clause(letter: &str, struck: bool) -> Clause {
        Clause {
            body: String::new(),
            header: String::new(),
            end: 1,
            stable_id: None,
            letter: Some(letter.to_string()),
            text: "body".into(),
            struck,
            draft: false,
            loc: Location {
                path: PathBuf::from("p.md"),
                line: 1,
            },
        }
    }

    #[test]
    fn struck_is_not_live() {
        let scan = Scan {
            laws: vec![Law {
                body: String::new(),
                end: 1,
                context: String::new(),
                aliases: Vec::new(),
                id: "k2m9x1abc".into(),
                name: "leftover".into(),
                loc: Location {
                    path: PathBuf::from("p.md"),
                    line: 1,
                },
                clauses: vec![clause("a", true)],
                struck: false,
                draft: false,
                public: false,
            }],
            ..Scan::default()
        };
        let graph = Graph::from_scan(&scan);
        let node = graph.by_id.get("k2m9x1abc.a").unwrap();
        assert!(!graph.is_live(node));
    }

    #[test]
    fn indexes_law_without_clauses() {
        let scan = Scan {
            laws: vec![Law {
                body: String::new(),
                end: 1,
                context: String::new(),
                aliases: Vec::new(),
                id: "abcdefgh1".into(),
                name: "bare law".into(),
                loc: Location {
                    path: PathBuf::from("p.md"),
                    line: 1,
                },
                clauses: vec![],
                struck: false,
                draft: false,
                public: false,
            }],
            ..Scan::default()
        };
        let graph = Graph::from_scan(&scan);
        let node = graph.by_id.get("abcdefgh1").unwrap();
        assert_eq!(node.name, "bare law");
        assert!(graph.is_live(node));
    }

    #[test]
    fn clause_lookup_resolves() {
        let scan = Scan {
            laws: vec![Law {
                draft: false,
                body: String::new(),
                end: 1,
                context: String::new(),
                aliases: Vec::new(),
                id: "abcdefgh1".into(),
                name: "law".into(),
                loc: Location {
                    path: PathBuf::from("p.md"),
                    line: 1,
                },
                clauses: vec![clause("a", false)],
                struck: false,
                public: false,
            }],
            ..Scan::default()
        };
        let graph = Graph::from_scan(&scan);
        let target = Target::Stable {
            id: "abcdefgh1".into(),
            letter: Some("a".into()),
        };
        let node = graph.lookup("law", &target).unwrap();
        assert_eq!(node.letter.as_deref(), Some("a"));
    }
}