use std::fs;
use std::path::Path;
use std::process;
use rhwp::provenance;
use rhwp::schema_registry::ENVELOPE_SCHEMA_VERSION;
use super::runtime::{edit_output_format, edit_serialize, edit_verify_report, EditOutputFormat};
use crate::{load_document, LoadError, EXIT_OK, EXIT_RUNTIME, EXIT_USAGE};
pub(crate) fn parse_field_key(key: &str) -> (&str, usize) {
let Some(open) = key.rfind('[') else {
return (key, 0);
};
if !key.ends_with(']') {
return (key, 0);
}
let inner = &key[open + 1..key.len() - 1];
match inner.parse::<usize>() {
Ok(n) => (&key[..open], n),
Err(_) => (key, 0),
}
}
pub(super) fn edit_fill_fields(args: &[String]) -> i32 {
let mut file_path: Option<&str> = None;
let mut data_arg: Option<&str> = None;
let mut out_path: Option<String> = None;
let mut dry_run = false;
let mut json_mode = false;
let mut verify_mode = false;
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--data" => {
i += 1;
match args.get(i) {
Some(v) => data_arg = Some(v),
None => {
eprintln!("오류: --data 뒤에 JSON 또는 @파일경로가 필요합니다.");
return EXIT_USAGE;
}
}
}
"-o" | "--output" => {
i += 1;
match args.get(i) {
Some(v) => out_path = Some(v.clone()),
None => {
eprintln!("오류: -o 뒤에 출력 파일 경로가 필요합니다.");
return EXIT_USAGE;
}
}
}
"--dry-run" => dry_run = true,
"--json" => json_mode = true,
"--verify" => verify_mode = true,
other if other.starts_with('-') => {
eprintln!("알 수 없는 옵션: {other}");
return EXIT_USAGE;
}
other => file_path = Some(other),
}
i += 1;
}
let (Some(file_path), Some(data_arg)) = (file_path, data_arg) else {
eprintln!("사용법: rhwp edit fill-fields <파일.hwp|파일.hwpx> --data <JSON|@파일> [-o <출력>] [--dry-run] [--json]");
return EXIT_USAGE;
};
let data_text = if let Some(path) = data_arg.strip_prefix('@') {
match fs::read_to_string(path) {
Ok(s) => s,
Err(e) => {
eprintln!("오류: --data 파일을 읽을 수 없습니다 - {}: {}", path, e);
return EXIT_RUNTIME;
}
}
} else {
data_arg.to_string()
};
let data: serde_json::Map<String, serde_json::Value> =
match serde_json::from_str::<serde_json::Value>(&data_text) {
Ok(serde_json::Value::Object(m)) => m,
Ok(_) => {
eprintln!("오류: --data 는 {{\"필드이름\":\"값\"}} 형식의 JSON 객체여야 합니다.");
return EXIT_USAGE;
}
Err(e) => {
eprintln!("오류: --data JSON 파싱 실패 - {}", e);
return EXIT_USAGE;
}
};
let outcome = match fill_fields_core(file_path, &data, out_path, dry_run, verify_mode) {
Ok(o) => o,
Err(message) => {
eprintln!("오류: {message}");
return EXIT_RUNTIME;
}
};
let FillOutcome {
envelope,
output_path,
verify_failed,
..
} = outcome;
if json_mode {
println!("{envelope}");
if verify_failed {
process::exit(3);
}
return EXIT_OK;
}
let empty: Vec<serde_json::Value> = Vec::new();
let filled = envelope["filled"].as_array().unwrap_or(&empty);
let not_found: Vec<&str> = envelope["notFound"]
.as_array()
.unwrap_or(&empty)
.iter()
.filter_map(|v| v.as_str())
.collect();
let confusable = envelope["confusable"].as_array().unwrap_or(&empty);
if dry_run {
println!("변경 예정: {} (필드 {}개)", file_path, filled.len());
} else {
println!(
"채우기 완료: {} → {} (필드 {}개)",
file_path,
output_path,
filled.len()
);
}
for f in filled {
println!(
" {} = {:?}",
f["name"].as_str().unwrap_or(""),
f["value"].as_str().unwrap_or("")
);
}
if !not_found.is_empty() {
println!(" 문서에 없는 필드 이름: {}", not_found.join(", "));
}
if verify_failed {
eprintln!("검증 실패(--verify): 저장본 재파싱 IR 차이 — 상세는 --json 또는 ir-diff");
process::exit(3);
}
for c in confusable {
eprintln!(
"경고: '{}' 과(와) 화면상 구별되지 않는 이름의 누름틀이 문서에 함께 있습니다 \
— 채운 칸이 의도한 칸인지 확인하세요.",
c["name"].as_str().unwrap_or("")
);
}
EXIT_OK
}
pub(crate) struct FillOutcome {
pub(crate) envelope: serde_json::Value,
output_path: String,
pub(crate) output_format: EditOutputFormat,
verify_failed: bool,
}
pub(crate) fn fill_fields_core(
file_path: &str,
data: &serde_json::Map<String, serde_json::Value>,
out_path: Option<String>,
dry_run: bool,
verify_mode: bool,
) -> Result<FillOutcome, String> {
let bytes = fs::read(file_path)
.map_err(|e| format!("파일을 읽을 수 없습니다 - {}: {}", file_path, e))?;
let mut doc = load_document(&bytes).map_err(|e| match e {
LoadError::NeedPassword => {
"비밀번호가 필요한 암호 문서입니다 (--password <pw> 로 전달)".to_string()
}
LoadError::WrongPassword => {
"비밀번호가 일치하지 않거나 암호화 데이터가 손상되었습니다".to_string()
}
LoadError::Other(msg) => format!("HWP 파싱 실패 - {}", msg),
})?;
let mut name_counts: std::collections::HashMap<String, usize> =
std::collections::HashMap::new();
let mut name_locs: std::collections::HashMap<String, Vec<(usize, usize)>> =
std::collections::HashMap::new();
for fi in doc.collect_all_fields().iter() {
if let Some(n) = fi.field.field_name() {
*name_counts.entry(n.to_string()).or_insert(0) += 1;
name_locs
.entry(n.to_string())
.or_default()
.push((fi.location.section_index, fi.location.para_index));
}
}
let mut changed_paras: Vec<(usize, usize)> = Vec::new();
let mut filled: Vec<serde_json::Value> = Vec::new();
let mut not_found: Vec<String> = Vec::new();
let mut ambiguous: Vec<serde_json::Value> = Vec::new();
let all_names: Vec<String> = name_counts.keys().cloned().collect();
let confusable_groups = rhwp::document_core::text_security::confusable_collisions(&all_names);
let mut confusable: Vec<serde_json::Value> = Vec::new();
for (key, value) in data {
let value_str = match value {
serde_json::Value::String(s) => s.clone(),
other => other.to_string(),
};
let (name, occurrence) = parse_field_key(key);
let total = name_counts.get(name).copied().unwrap_or(0);
if total == 0 || occurrence >= total {
not_found.push(key.clone());
continue;
}
if occurrence == 0 && total > 1 && !key.contains('[') {
ambiguous.push(serde_json::json!({
"name": name,
"matched": 1,
"total": total,
}));
}
if let Some((_, group)) = confusable_groups
.iter()
.find(|(_, g)| g.iter().any(|n| n == name))
{
let others: Vec<&String> = group.iter().filter(|n| *n != name).collect();
confusable.push(serde_json::json!({
"name": name,
"lookalikes": others,
"note": "화면상 구별되지 않는 이름의 누름틀이 이 문서에 함께 있습니다 — 채운 칸이 의도한 칸인지 확인하세요.",
}));
}
if dry_run {
filled.push(
serde_json::json!({ "name": name, "occurrence": occurrence, "value": value_str }),
);
continue;
}
doc.set_field_value_by_name_at(name, occurrence, &value_str)
.map_err(|e| format!("필드 '{}' 설정 실패 - {}", key, e))?;
if let Some(loc) = name_locs.get(name).and_then(|l| l.get(occurrence)) {
changed_paras.push(*loc);
}
filled.push(
serde_json::json!({ "name": name, "occurrence": occurrence, "value": value_str }),
);
}
let out_format = edit_output_format(&bytes, out_path.as_deref());
let output_path = out_path.unwrap_or_else(|| {
let input = Path::new(file_path);
let stem = input
.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_else(|| "output".to_string());
let name = format!("{}_filled.{}", stem, out_format.ext());
match input.parent() {
Some(dir) if !dir.as_os_str().is_empty() => {
dir.join(name).to_string_lossy().to_string()
}
_ => name,
}
});
let mut verify_report = serde_json::Value::Null;
let mut verify_failed = false;
if !dry_run {
let out_bytes = edit_serialize(&mut doc, out_format)
.map_err(|e| format!("{} 직렬화 실패 - {}", out_format.label().to_uppercase(), e))?;
fs::write(&output_path, &out_bytes)
.map_err(|e| format!("출력 쓰기 실패 - {}: {}", output_path, e))?;
if verify_mode {
let cross = out_format == EditOutputFormat::Hwp
&& rhwp::parser::detect_format(&bytes) == rhwp::parser::FileFormat::Hwpx;
let (report, failed) = edit_verify_report(&doc, &out_bytes, cross);
verify_report = report;
verify_failed = failed;
}
}
let changed_pages = if dry_run {
serde_json::Value::Null
} else {
match doc.pages_covering_paragraphs(&changed_paras) {
Some(pages) => serde_json::json!(pages),
None => serde_json::Value::Null,
}
};
let mut envelope = serde_json::json!({
"schemaVersion": ENVELOPE_SCHEMA_VERSION,
"source": file_path,
"dryRun": dry_run,
"changedPages": changed_pages,
"filledCount": filled.len(),
"filled": filled,
"notFound": not_found,
"ambiguous": ambiguous,
"confusable": confusable,
});
if !dry_run {
envelope["output"] = serde_json::Value::String(output_path.clone());
envelope["outputFormat"] = serde_json::Value::String(out_format.label().to_string());
envelope["verify"] = verify_report;
}
Ok(FillOutcome {
envelope: provenance::marked(envelope, "edit"),
output_path,
output_format: out_format,
verify_failed,
})
}