use std::fs;
use crate::{
collect_field_records, load_document, provenance, ENVELOPE_SCHEMA_VERSION, EXIT_OK,
EXIT_RUNTIME, EXIT_USAGE,
};
fn explain_table_summary(
grid: &rhwp::document_core::queries::table_extract::TableGrid,
) -> serde_json::Value {
let has_merged_cells = grid.cells.iter().any(|c| c.row_span > 1 || c.col_span > 1);
serde_json::json!({
"index": grid.index,
"rows": grid.rows,
"cols": grid.cols,
"hasMergedCells": has_merged_cells,
})
}
fn explain_table_phrase(t: &serde_json::Value) -> String {
let human_no = t["index"].as_u64().unwrap_or(0) + 1;
let rows = t["rows"].as_u64().unwrap_or(0);
let cols = t["cols"].as_u64().unwrap_or(0);
if t["hasMergedCells"] == true {
format!("표 {human_no}({rows}×{cols}, 병합 셀 있음)")
} else {
format!("표 {human_no}({rows}×{cols})")
}
}
fn explain_summary(
format_label: &str,
page_count: u32,
para_count: usize,
tables: &[serde_json::Value],
field_names: &[String],
footnote_count: usize,
endnote_count: usize,
encrypted: bool,
) -> String {
let mut lines = Vec::new();
lines.push(format!(
"이 문서는 {format_label} 형식, {page_count}쪽, 문단 {para_count}개다."
));
if tables.is_empty() {
lines.push("표는 없다.".to_string());
} else {
let phrases: Vec<String> = tables.iter().map(explain_table_phrase).collect();
lines.push(format!(
"표가 {}개 있다 — {}.",
tables.len(),
phrases.join(", ")
));
}
if field_names.is_empty() {
lines.push("누름틀은 없다.".to_string());
} else {
lines.push(format!(
"누름틀이 {}개 있다 — 이름: {}.",
field_names.len(),
field_names.join(", ")
));
}
if footnote_count == 0 && endnote_count == 0 {
lines.push("각주와 미주는 모두 없다.".to_string());
} else {
lines.push(format!(
"각주가 {footnote_count}개, 미주가 {endnote_count}개 있다."
));
}
lines.push(if encrypted {
"암호로 보호돼 있다.".to_string()
} else {
"암호로 보호돼 있지 않다.".to_string()
});
lines.join("\n")
}
fn explain_json_value(
file_path: &str,
format_label: &str,
page_count: u32,
para_count: usize,
tables: Vec<serde_json::Value>,
field_names: Vec<String>,
footnote_count: usize,
endnote_count: usize,
encrypted: bool,
) -> serde_json::Value {
let summary = explain_summary(
format_label,
page_count,
para_count,
&tables,
&field_names,
footnote_count,
endnote_count,
encrypted,
);
provenance::marked(
serde_json::json!({
"schemaVersion": ENVELOPE_SCHEMA_VERSION,
"source": file_path,
"format": format_label,
"pageCount": page_count,
"paragraphCount": para_count,
"tables": tables,
"fields": field_names,
"footnoteCount": footnote_count,
"endnoteCount": endnote_count,
"encrypted": encrypted,
"summary": summary,
}),
"explain",
)
}
pub(crate) fn explain_document(args: &[String]) -> i32 {
let mut json_mode = false;
let mut file_path: Option<&str> = None;
for arg in args {
match arg.as_str() {
"--json" => json_mode = true,
other if other.starts_with('-') => {
eprintln!("알 수 없는 옵션: {other}");
return EXIT_USAGE;
}
other => {
if file_path.replace(other).is_some() {
eprintln!("오류: 입력 파일은 하나만 지정할 수 있습니다: {other}");
return EXIT_USAGE;
}
}
}
}
let Some(file_path) = file_path else {
eprintln!("사용법: rhwp explain <파일.hwp|파일.hwpx|파일.hml> [--json]");
return EXIT_USAGE;
};
let data = match fs::read(file_path) {
Ok(d) => d,
Err(e) => {
eprintln!("오류: 파일을 읽을 수 없습니다 - {}: {}", file_path, e);
return EXIT_RUNTIME;
}
};
let detected_format = rhwp::parser::detect_format(&data);
let doc = match load_document(&data) {
Ok(d) => d,
Err(e) => return e.report(),
};
let document = doc.document();
let format_label = match detected_format {
rhwp::parser::FileFormat::Hwp => "HWP5",
rhwp::parser::FileFormat::Hwpx => "HWPX",
rhwp::parser::FileFormat::Hwp3 => "HWP3",
rhwp::parser::FileFormat::Hml => "HML",
rhwp::parser::FileFormat::Pdf => "PDF",
rhwp::parser::FileFormat::DrmProtected => "DRM",
rhwp::parser::FileFormat::Empty => "빈 파일",
rhwp::parser::FileFormat::Unknown => "알 수 없음",
};
let page_count = doc.page_count();
let para_count: usize = document.sections.iter().map(|s| s.paragraphs.len()).sum();
use rhwp::document_core::queries::table_extract::extract_tables;
let tables: Vec<serde_json::Value> = extract_tables(document)
.iter()
.map(explain_table_summary)
.collect();
let field_records = collect_field_records(&doc);
let field_names: Vec<String> = field_records
.iter()
.map(|f| f["name"].as_str().unwrap_or("").to_string())
.collect();
let notes = rhwp::document_core::queries::explain::count_notes(document);
let encrypted = document.header.encrypted;
if json_mode {
let envelope = explain_json_value(
file_path,
format_label,
page_count,
para_count,
tables,
field_names,
notes.footnote_count,
notes.endnote_count,
encrypted,
);
println!("{envelope}");
return EXIT_OK;
}
let summary = explain_summary(
format_label,
page_count,
para_count,
&tables,
&field_names,
notes.footnote_count,
notes.endnote_count,
encrypted,
);
println!("{summary}");
EXIT_OK
}