# -*- coding: utf-8 -*-
"""CG UndoCommand /undo 撤销命令（Phase 8 Tier 2）

借鉴 zhikuncode UndoCommand.java：
- 找到当前 session 最新可回退事务
- 调 FileHistoryService.rewind 批量回退
- 输出受影响文件列表
- 已 rewind 的事务自动跳到下一个
"""
from __future__ import annotations

from typing import Optional

from ..history import FileHistoryService

# 全局单例，由 main.py 在启动时初始化
_HISTORY_SERVICE: Optional[FileHistoryService] = None


def init_history_service(service: FileHistoryService) -> None:
    """注入 FileHistoryService 实例。"""
    global _HISTORY_SERVICE
    _HISTORY_SERVICE = service


def get_history_service() -> Optional[FileHistoryService]:
    """返回当前注入的 FileHistoryService 实例。"""
    return _HISTORY_SERVICE


def handle_undo(session) -> str:
    r"""/undo 命令处理：撤销最近一轮 AI 文件编辑。

    Args:
        session: Session 实例，需有 session_id 属性

    Returns:
        可读的结果字符串
    """
    if _HISTORY_SERVICE is None:
        return "[ERR] 文件历史服务未初始化，无法撤销"

    # 与 main.py:744 保持一致：session 无 session_id 属性时回退到 "default"
    session_id = getattr(session, "session_id", "") or "default"

    # 找到最新可回退事务
    record = _HISTORY_SERVICE.get_latest_transaction(session_id)
    if record is None:
        return "[INFO] 当前会话无可撤销的文件编辑"

    # 执行回退
    result = _HISTORY_SERVICE.rewind(record.transaction_id)
    if not result.success:
        return (
            f"[ERR] 撤销失败: {result.error or '未知错误'}\n"
            f"事务 id: {result.transaction_id}"
        )

    # 输出受影响文件
    lines = [
        f"[OK] 已撤销事务 {result.transaction_id[:8]}...",
        f"影响文件 {len(result.affected_files)} 个：",
    ]
    for path in result.affected_files:
        lines.append(f"  - {path}")
    return "\n".join(lines)


def handle_redo(session) -> str:
    r"""/redo 命令处理：恢复最近一次被 /undo 撤销的修改。

    Args:
        session: Session 实例，需有 session_id 属性

    Returns:
        可读的结果字符串
    """
    if _HISTORY_SERVICE is None:
        return "[ERR] 文件历史服务未初始化，无法恢复"

    session_id = getattr(session, "session_id", "") or "default"

    # 找到最近一次被撤销的事务
    record = _HISTORY_SERVICE.get_latest_rewound_transaction(session_id)
    if record is None:
        return "[INFO] 当前会话无可恢复的撤销（先用 /undo 撤销一次）"

    # 执行恢复
    result = _HISTORY_SERVICE.redo(record.transaction_id)
    if not result.success:
        return (
            f"[ERR] 恢复失败: {result.error or '未知错误'}\n"
            f"事务 id: {result.transaction_id}"
        )

    lines = [
        f"[OK] 已恢复事务 {result.transaction_id[:8]}...",
        f"影响文件 {len(result.affected_files)} 个：",
    ]
    for path in result.affected_files:
        lines.append(f"  - {path}")
    return "\n".join(lines)
