use crate::envelope::{
envelope, load_core, page_texts, print_json, read_file, EXIT_OK, EXIT_RUNTIME, EXIT_USAGE,
};
use serde_json::{json, Value};
const MIN_LINE_CHARS: usize = 4;
struct Measured {
source: String,
bytes: u64,
utf8_chars: u64,
utf16le_chars: u64,
native_chars: u64,
recovery_utf8: f64,
recovery_utf16le: f64,
sampled_chars: u64,
}
fn decode_utf16le(data: &[u8]) -> String {
let units: Vec<u16> = data
.chunks_exact(2)
.map(|pair| u16::from_le_bytes([pair[0], pair[1]]))
.collect();
String::from_utf16_lossy(&units)
}
fn recovery_percent(lines: &[&str], decoded: &str, total: u64) -> f64 {
if total == 0 {
return 0.0;
}
let hit: u64 = lines
.iter()
.filter(|line| decoded.contains(**line))
.map(|line| line.chars().count() as u64)
.sum();
(hit as f64) * 100.0 / (total as f64)
}
fn measure(path: &str) -> Result<Measured, String> {
let data = read_file(path)?;
let core =
load_core(&data).map_err(|fail| format!("문서를 열 수 없습니다: {}", fail.message))?;
let pages = page_texts(&core)?;
let utf8 = String::from_utf8_lossy(&data);
let utf16 = decode_utf16le(&data);
let native_chars: u64 = pages.iter().map(|p| p.chars().count() as u64).sum();
let joined = pages.join("\n");
let lines: Vec<&str> = joined
.lines()
.map(str::trim)
.filter(|l| l.chars().count() >= MIN_LINE_CHARS)
.collect();
let sampled_chars: u64 = lines.iter().map(|l| l.chars().count() as u64).sum();
Ok(Measured {
source: path.to_string(),
bytes: data.len() as u64,
utf8_chars: utf8.chars().count() as u64,
utf16le_chars: utf16.chars().count() as u64,
native_chars,
recovery_utf8: recovery_percent(&lines, &utf8, sampled_chars),
recovery_utf16le: recovery_percent(&lines, &utf16, sampled_chars),
sampled_chars,
})
}
fn ratio(numerator: u64, denominator: u64) -> Value {
if denominator == 0 {
return Value::Null;
}
json!(((numerator as f64 / denominator as f64) * 10.0).round() / 10.0)
}
fn round1(v: f64) -> Value {
json!((v * 10.0).round() / 10.0)
}
pub fn run(args: &[String]) -> i32 {
const USAGE: &str = "사용법: rhwp-agent context-cost <파일...> [--json]";
let mut json_mode = false;
let mut files: Vec<String> = Vec::new();
for arg in args {
match arg.as_str() {
"--json" => json_mode = true,
other if other.starts_with('-') => {
eprintln!("오류: 알 수 없는 옵션입니다 - {other}");
eprintln!("{USAGE}");
return EXIT_USAGE;
}
positional => files.push(positional.to_string()),
}
}
if files.is_empty() {
eprintln!("오류: 대상 파일을 하나 이상 지정해주세요.");
eprintln!("{USAGE}");
return EXIT_USAGE;
}
let mut measured = Vec::with_capacity(files.len());
for path in &files {
match measure(path) {
Ok(m) => measured.push(m),
Err(message) => {
eprintln!("오류: {path}: {message}");
return EXIT_RUNTIME;
}
}
}
let total_bytes: u64 = measured.iter().map(|m| m.bytes).sum();
let total_utf8: u64 = measured.iter().map(|m| m.utf8_chars).sum();
let total_native: u64 = measured.iter().map(|m| m.native_chars).sum();
if json_mode {
let items: Vec<Value> = measured
.iter()
.map(|m| {
json!({
"source": m.source,
"bytes": m.bytes,
"rawChars": { "utf8": m.utf8_chars, "utf16le": m.utf16le_chars },
"nativeChars": m.native_chars,
"charRatio": ratio(m.utf8_chars, m.native_chars),
"recoveryPercent": {
"utf8": round1(m.recovery_utf8),
"utf16le": round1(m.recovery_utf16le),
},
"sampledChars": m.sampled_chars,
})
})
.collect();
let payload = json!({
"unit": "chars",
"unitNote": "토크나이저는 모델마다 다르므로 토큰이 아니라 문자를 센다. 배수는 모델 간 이식 가능한 하한으로 읽으라.",
"recoveryNote": format!("본문 줄({MIN_LINE_CHARS}자 이상)이 원문 그대로 디코딩 안에 있는 비율. 짧은 줄은 우연 일치를 만들어 제외한다."),
"fileCount": measured.len(),
"files": items,
"summary": {
"bytes": total_bytes,
"rawChars": { "utf8": total_utf8 },
"nativeChars": total_native,
"charRatio": ratio(total_utf8, total_native),
},
});
print_json(&envelope("context-cost", payload, &[]));
} else {
crate::outln!("rhwp-agent context-cost — 파일 {}개", measured.len());
crate::outln!(" 단위는 문자(토큰 아님). 배수는 모델 간 이식 가능한 하한이다.");
for m in &measured {
crate::outln!(" {}", m.source);
crate::outln!(
" 바이트 {} · 그대로 싣기(UTF-8) {}자 · 문서 본문 {}자",
m.bytes,
m.utf8_chars,
m.native_chars
);
let ratio_text = if m.native_chars == 0 {
"정의 불가(본문 0자)".to_string()
} else {
format!("{:.1}배", m.utf8_chars as f64 / m.native_chars as f64)
};
crate::outln!(
" 문자 배수 {ratio_text} · 복원율 UTF-8 {:.1}% · UTF-16LE {:.1}%",
m.recovery_utf8,
m.recovery_utf16le
);
}
}
EXIT_OK
}