using System.IO;
using System.Text;
using System.Text.Json;

namespace AxCopilot.Services.Agent;

/// <summary>파일 전체를 새로 쓰는 도구. 새 파일 생성 또는 기존 파일 덮어쓰기.</summary>
public class FileWriteTool : IAgentTool
{
    public string Name => "file_write";
    public string Description => "Write content to a file. Creates new file or overwrites existing. Parent directories are created automatically.";

    public ToolParameterSchema Parameters => new()
    {
        Properties = new()
        {
            ["path"] = new() { Type = "string", Description = "File path to write (absolute or relative to work folder)" },
            ["content"] = new() { Type = "string", Description = "Content to write to the file" },
        },
        Required = ["path", "content"]
    };

    public async Task<ToolResult> ExecuteAsync(JsonElement args, AgentContext context, CancellationToken ct)
    {
        var path = args.GetProperty("path").GetString() ?? "";
        var content = args.GetProperty("content").GetString() ?? "";

        var fullPath = FileReadTool.ResolvePath(path, context.WorkFolder);

        if (!context.IsPathAllowed(fullPath))
            return ToolResult.Fail($"경로 접근 차단: {fullPath}");

        if (!await context.CheckWritePermissionAsync(Name, fullPath))
            return ToolResult.Fail($"쓰기 권한 거부: {fullPath}");

        try
        {
            var dir = Path.GetDirectoryName(fullPath);
            if (!string.IsNullOrEmpty(dir))
                Directory.CreateDirectory(dir);

            await File.WriteAllTextAsync(fullPath, content, Encoding.UTF8, ct);
            var lines = content.Split('\n').Length;
            return ToolResult.Ok($"파일 저장 완료: {fullPath} ({lines} lines, {content.Length} chars)", fullPath);
        }
        catch (Exception ex)
        {
            return ToolResult.Fail($"파일 쓰기 실패: {ex.Message}");
        }
    }
}
