# -*- coding: utf-8 -*-
"""CH CompactCommand 手动压缩上下文（Phase 8 Tier 2）

借鉴 zhikuncode CompactCommand.java（95 行）：
- /compact [custom_instruction] 手动触发上下文压缩
- 调用现有 SimpleTruncationEngine.compress()
- 显示压缩前后 token 数对比

集成点：main.py handle_slash_command 注册 /compact。
"""
from typing import Optional


def handle_compact(session, engine, custom_instruction: Optional[str]) -> str:
    """/compact 命令处理：手动触发上下文压缩。

    Args:
        session: Session 实例，需有 messages 属性
        engine: SimpleTruncationEngine 实例，需有 estimate_tokens / compress 方法
        custom_instruction: 用户自定义压缩指令（如 "focus on API design decisions"）

    Returns:
        成功/失败的可读消息字符串
    """
    if engine is None:
        return "[ERR] 上下文引擎未初始化，无法压缩"

    try:
        before_tokens = engine.estimate_tokens(session.messages)
        compressed = engine.compress(
            session.messages,
            focus_topic=custom_instruction,
        )
        after_tokens = engine.estimate_tokens(compressed)
        session.messages = compressed
        saved = max(0, before_tokens - after_tokens)
        return (
            f"[OK] 压缩完成：{before_tokens} → {after_tokens} tokens"
            f"（节省 {saved}）"
        )
    except Exception as exc:
        return f"[ERR] 压缩失败：{exc}"
