# -*- coding: utf-8 -*-
"""
文件写入工具
创建新文件或覆盖写入已有文件
"""
import os
from .base import Tool, coerce_bool
from .file_cache import get_default_cache
from .file_io import AtomicFileWriter
from ..security.path_security import get_default_service as get_path_security


class FileWriteTool(Tool):
    """创建或覆盖写入文件的工具。"""

    @property
    def name(self) -> str:
        return "file_write"

    @property
    def description(self) -> str:
        return "创建新文件或覆盖写入已有文件。"

    @property
    def parameters(self) -> dict:
        return {
            "type": "object",
            "properties": {
                "path": {"type": "string", "description": "文件路径"},
                "content": {"type": "string", "description": "文件内容"},
                "append": {"type": "boolean", "description": "是否追加，默认false"}
            },
            "required": ["path", "content"]
        }

    def execute(self, path: str, content: str, append: bool = False) -> dict:
        """写入文件内容"""
        # PathSecurityService 5 重校验（Phase 6 Tier 1-5 AP）
        # - 符号链接逃逸 / 路径穿越 / 工作目录边界 / 受保护路径 / Windows 绕过
        sec = get_path_security()
        check = sec.check_write(path)
        if not check.allowed:
            return {"success": False, "error": check.reason}
        if check.needs_confirmation:
            return {"success": False, "error": f"需用户确认: {check.reason}"}

        # 兼容 LLM 将 append 序列化为字符串 "false"/"true" 的情形
        append = coerce_bool(append, default=False)

        try:
            # 使用 AtomicFileWriter 原子写入（Phase 6 Tier 1-3 AO）
            # - 普通写入：临时文件 → fsync → os.replace（CAS 原子替换）
            # - 追加模式：直接追加
            # - 大文件（>10MB）：跳过原子写入避免临时空间翻倍
            AtomicFileWriter.write(path, content, encoding="utf-8", append=append)
            # 失效文件状态缓存（Phase 6 AQ）
            get_default_cache().invalidate(path)
            return {"success": True, "path": path, "mode": "append" if append else "write"}
        except Exception as e:
            return {"success": False, "error": str(e)}
