Skip to main content

clm_rust_core/layer1/
action_manipulators.rs

1#![allow(unused_imports)]
2use super::*;
3
4pub struct DocumentManipulator;
5
6impl DocumentManipulator {
7    pub fn split(data: &str, params: &HashMap<String, Value>) -> Result<HashMap<String, String>, String> {
8        let delimiter = params.get("delimiter").and_then(|v| v.as_str()).unwrap_or("# ");
9        let mut results = HashMap::new();
10        let parts: Vec<&str> = data.split(delimiter).collect();
11        if parts.len() <= 1 {
12            results.insert("document".to_string(), data.to_string());
13            return Ok(results);
14        }
15
16        let mut idx = 1;
17        for part in &parts[1..] {
18            let key = format!("section_{}", idx);
19            let content = format!("{}{}", delimiter, part.trim());
20            results.insert(key, content);
21            idx += 1;
22        }
23        if !parts[0].trim().is_empty() {
24            results.insert("intro".to_string(), parts[0].trim().to_string());
25        }
26        Ok(results)
27    }
28
29    pub fn substitute(data: &str, params: &HashMap<String, Value>) -> Result<String, String> {
30        let mut res = data.to_string();
31        if let (Some(target), Some(replacement)) = (
32            params.get("target_header").and_then(|v| v.as_str()),
33            params.get("replacement_header").and_then(|v| v.as_str()),
34        ) {
35            res = res.replace(target, replacement);
36        } else if let Some(Value::Object(replacements)) = params.get("replacements") {
37            for (old, new_val) in replacements {
38                if let Some(new_str) = new_val.as_str() {
39                    res = res.replace(old, new_str);
40                }
41            }
42        }
43        Ok(res)
44    }
45
46    pub fn augment(data: &str, params: &HashMap<String, Value>) -> Result<String, String> {
47        let mut res = data.to_string();
48        if let Some(content) = params.get("content").and_then(|v| v.as_str()) {
49            if !res.ends_with('\n') {
50                res.push('\n');
51            }
52            res.push_str(content);
53            if !res.ends_with('\n') {
54                res.push('\n');
55            }
56        }
57        Ok(res)
58    }
59
60    pub fn exclude(data: &str, params: &HashMap<String, Value>) -> Result<String, String> {
61        let section_title = params.get("section_title").and_then(|v| v.as_str()).unwrap_or("");
62        let mut lines = Vec::new();
63        let mut skipping = false;
64        for line in data.lines() {
65            if line.starts_with('#') && line.contains(section_title) && !section_title.is_empty() {
66                skipping = true;
67                continue;
68            }
69            if skipping && line.starts_with('#') {
70                skipping = false;
71            }
72            if !skipping {
73                lines.push(line);
74            }
75        }
76        let mut res = lines.join("\n");
77        if data.ends_with('\n') {
78            res.push('\n');
79        }
80        Ok(res)
81    }
82
83    pub fn invert(data: &str, _params: &HashMap<String, Value>) -> Result<String, String> {
84        let sections: Vec<&str> = data.split("\n#").collect();
85        if sections.len() <= 1 {
86            return Ok(data.to_string());
87        }
88        let intro = sections[0];
89        let mut rest: Vec<String> = sections[1..].iter().map(|s| format!("#{}", s)).collect();
90        rest.reverse();
91        Ok(format!("{}\n{}", intro.trim(), rest.join("\n")))
92    }
93
94    pub fn port(data: &str, params: &HashMap<String, Value>) -> Result<String, String> {
95        let target_fmt = params.get("target_format").and_then(|v| v.as_str()).unwrap_or("text").to_lowercase();
96        if target_fmt == "html" {
97            let mut html = String::new();
98            for line in data.lines() {
99                if let Some(h1) = line.strip_prefix("# ") {
100                    html.push_str(&format!("<h1>{}</h1>\n", h1.trim()));
101                } else if let Some(h2) = line.strip_prefix("## ") {
102                    html.push_str(&format!("<h2>{}</h2>\n", h2.trim()));
103                } else if !line.trim().is_empty() {
104                    html.push_str(&format!("<p>{}</p>\n", line.trim()));
105                }
106            }
107            return Ok(html);
108        }
109        // plain text: strip #, *, `
110        let plain = data.replace(['#', '*', '`'], "");
111        Ok(plain)
112    }
113}
114
115pub struct StructuredManipulator;
116
117impl StructuredManipulator {
118    pub fn split(data: &str, params: &HashMap<String, Value>) -> Result<HashMap<String, String>, String> {
119        let v: Value = serde_json::from_str(data)
120            .or_else(|_| serde_yaml::from_str(data))
121            .map_err(|e| format!("Invalid structured data: {}", e))?;
122
123        let mut partitions = HashMap::new();
124        if let Value::Object(map) = v {
125            if let Some(Value::Object(groups)) = params.get("groups") {
126                for (g_name, g_keys) in groups {
127                    if let Value::Array(keys) = g_keys {
128                        let mut sub = serde_json::Map::new();
129                        for k in keys {
130                            if let Some(ks) = k.as_str()
131                                && let Some(val) = map.get(ks) {
132                                    sub.insert(ks.to_string(), val.clone());
133                                }
134                        }
135                        partitions.insert(g_name.clone(), serde_json::to_string_pretty(&Value::Object(sub)).unwrap());
136                    }
137                }
138                return Ok(partitions);
139            }
140            let keys: Vec<&String> = map.keys().collect();
141            let mid = keys.len() / 2;
142            let mut part1 = serde_json::Map::new();
143            let mut part2 = serde_json::Map::new();
144            for (i, k) in keys.iter().enumerate() {
145                if i < mid {
146                    part1.insert((*k).clone(), map[*k].clone());
147                } else {
148                    part2.insert((*k).clone(), map[*k].clone());
149                }
150            }
151            partitions.insert("part_1".to_string(), serde_json::to_string_pretty(&Value::Object(part1)).unwrap());
152            partitions.insert("part_2".to_string(), serde_json::to_string_pretty(&Value::Object(part2)).unwrap());
153            return Ok(partitions);
154        }
155        partitions.insert("all".to_string(), data.to_string());
156        Ok(partitions)
157    }
158
159    pub fn substitute(data: &str, params: &HashMap<String, Value>) -> Result<String, String> {
160        let mut v: Value = serde_json::from_str(data)
161            .or_else(|_| serde_yaml::from_str(data))
162            .map_err(|e| format!("Invalid structured data: {}", e))?;
163
164        if let (Value::Object(map), Some(Value::Object(replacements))) = (&mut v, params.get("replacements")) {
165            for (k, new_val) in replacements {
166                if map.contains_key(k) {
167                    map.insert(k.clone(), new_val.clone());
168                }
169            }
170        }
171        serde_json::to_string_pretty(&v).map_err(|e| e.to_string())
172    }
173
174    pub fn augment(data: &str, params: &HashMap<String, Value>) -> Result<String, String> {
175        let mut v: Value = serde_json::from_str(data)
176            .or_else(|_| serde_yaml::from_str(data))
177            .map_err(|e| format!("Invalid structured data: {}", e))?;
178
179        if let (Value::Object(map), Some(Value::Object(fields))) = (&mut v, params.get("fields")) {
180            for (k, val) in fields {
181                map.insert(k.clone(), val.clone());
182            }
183        }
184        serde_json::to_string_pretty(&v).map_err(|e| e.to_string())
185    }
186
187    pub fn exclude(data: &str, params: &HashMap<String, Value>) -> Result<String, String> {
188        let mut v: Value = serde_json::from_str(data)
189            .or_else(|_| serde_yaml::from_str(data))
190            .map_err(|e| format!("Invalid structured data: {}", e))?;
191
192        let mut drop_keys = Vec::new();
193        if let Some(Value::Array(keys)) = params.get("keys") {
194            for k in keys {
195                if let Some(s) = k.as_str() {
196                    drop_keys.push(s.to_string());
197                }
198            }
199        }
200
201        fn prune(val: &mut Value, drop: &[String]) {
202            match val {
203                Value::Object(map) => {
204                    for k in drop {
205                        map.remove(k);
206                    }
207                    for (_, child) in map.iter_mut() {
208                        prune(child, drop);
209                    }
210                }
211                Value::Array(arr) => {
212                    for child in arr.iter_mut() {
213                        prune(child, drop);
214                    }
215                }
216                _ => {}
217            }
218        }
219        prune(&mut v, &drop_keys);
220        serde_json::to_string_pretty(&v).map_err(|e| e.to_string())
221    }
222
223    pub fn invert(data: &str, _params: &HashMap<String, Value>) -> Result<String, String> {
224        let v: Value = serde_json::from_str(data)
225            .or_else(|_| serde_yaml::from_str(data))
226            .map_err(|e| format!("Invalid structured data: {}", e))?;
227
228        match v {
229            Value::Object(map) => {
230                let mut inverted = serde_json::Map::new();
231                for (k, val) in map {
232                    let val_str = match val {
233                        Value::String(s) => s,
234                        other => other.to_string(),
235                    };
236                    inverted.insert(val_str, Value::String(k));
237                }
238                serde_json::to_string_pretty(&Value::Object(inverted)).map_err(|e| e.to_string())
239            }
240            Value::Array(mut arr) => {
241                arr.reverse();
242                serde_json::to_string_pretty(&Value::Array(arr)).map_err(|e| e.to_string())
243            }
244            other => serde_json::to_string_pretty(&other).map_err(|e| e.to_string()),
245        }
246    }
247
248    pub fn port(data: &str, params: &HashMap<String, Value>) -> Result<String, String> {
249        let mut v: Value = serde_json::from_str(data)
250            .or_else(|_| serde_yaml::from_str(data))
251            .map_err(|e| format!("Invalid structured data: {}", e))?;
252
253        if let Some(target_runtime) = params.get("target_runtime").and_then(|r| r.as_str())
254            && let Value::Object(map) = &mut v {
255                map.insert("target_runtime".to_string(), Value::String(target_runtime.to_string()));
256            }
257
258        let target_fmt = params.get("target_format").and_then(|v| v.as_str()).unwrap_or("json").to_lowercase();
259        if target_fmt == "yaml" || target_fmt == crate::layer0::vocabulary_types::MIME_APPLICATION_YAML {
260            serde_yaml::to_string(&v).map_err(|e| e.to_string())
261        } else {
262            serde_json::to_string_pretty(&v).map_err(|e| e.to_string())
263        }
264    }
265}
266
267// ── Rule / Invariant Evaluator ──────────────────────────────────────────────
268