using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace AxCopilot.Services.Agent;

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
	{
		get
		{
			ToolParameterSchema obj = new ToolParameterSchema
			{
				Properties = new Dictionary<string, ToolProperty>
				{
					["path"] = new ToolProperty
					{
						Type = "string",
						Description = "File path to write (absolute or relative to work folder)"
					},
					["content"] = new ToolProperty
					{
						Type = "string",
						Description = "Content to write to the file"
					}
				}
			};
			int num = 2;
			List<string> list = new List<string>(num);
			CollectionsMarshal.SetCount(list, num);
			Span<string> span = CollectionsMarshal.AsSpan(list);
			span[0] = "path";
			span[1] = "content";
			obj.Required = list;
			return obj;
		}
	}

	public async Task<ToolResult> ExecuteAsync(JsonElement args, AgentContext context, CancellationToken ct)
	{
		string path = args.GetProperty("path").GetString() ?? "";
		string content = args.GetProperty("content").GetString() ?? "";
		string 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
		{
			string dir = Path.GetDirectoryName(fullPath);
			if (!string.IsNullOrEmpty(dir))
			{
				Directory.CreateDirectory(dir);
			}
			await File.WriteAllTextAsync(fullPath, content, Encoding.UTF8, ct);
			int lines = content.Split('\n').Length;
			return ToolResult.Ok($"파일 저장 완료: {fullPath} ({lines} lines, {content.Length} chars)", fullPath);
		}
		catch (Exception ex)
		{
			return ToolResult.Fail("파일 쓰기 실패: " + ex.Message);
		}
	}
}
