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

namespace AxCopilot.Services.Agent;

/// <summary>Base64/URL 인코딩·디코딩 도구.</summary>
public class Base64Tool : IAgentTool
{
    public string Name => "base64_tool";
    public string Description =>
        "Encode or decode Base64 and URL strings. Actions: " +
        "'b64encode' — encode text to Base64; " +
        "'b64decode' — decode Base64 to text; " +
        "'urlencode' — URL-encode text; " +
        "'urldecode' — URL-decode text; " +
        "'b64file' — encode a file to Base64 (max 5MB).";

    public ToolParameterSchema Parameters => new()
    {
        Properties = new()
        {
            ["action"] = new()
            {
                Type = "string",
                Description = "Action to perform",
                Enum = ["b64encode", "b64decode", "urlencode", "urldecode", "b64file"],
            },
            ["text"] = new()
            {
                Type = "string",
                Description = "Text to encode/decode",
            },
            ["file_path"] = new()
            {
                Type = "string",
                Description = "File path for b64file action",
            },
        },
        Required = ["action"],
    };

    public Task<ToolResult> ExecuteAsync(JsonElement args, AgentContext context, CancellationToken ct = default)
    {
        var action = args.GetProperty("action").GetString() ?? "";
        var text = args.TryGetProperty("text", out var t) ? t.GetString() ?? "" : "";

        try
        {
            return Task.FromResult(action switch
            {
                "b64encode" => ToolResult.Ok(Convert.ToBase64String(Encoding.UTF8.GetBytes(text))),
                "b64decode" => ToolResult.Ok(Encoding.UTF8.GetString(Convert.FromBase64String(text))),
                "urlencode" => ToolResult.Ok(Uri.EscapeDataString(text)),
                "urldecode" => ToolResult.Ok(Uri.UnescapeDataString(text)),
                "b64file"   => EncodeFile(args, context),
                _           => ToolResult.Fail($"Unknown action: {action}"),
            });
        }
        catch (FormatException)
        {
            return Task.FromResult(ToolResult.Fail("Invalid Base64 string"));
        }
        catch (Exception ex)
        {
            return Task.FromResult(ToolResult.Fail($"오류: {ex.Message}"));
        }
    }

    private static ToolResult EncodeFile(JsonElement args, AgentContext context)
    {
        if (!args.TryGetProperty("file_path", out var fp))
            return ToolResult.Fail("'file_path' is required for b64file action");
        var path = fp.GetString() ?? "";
        if (!Path.IsPathRooted(path)) path = Path.Combine(context.WorkFolder, path);
        if (!File.Exists(path)) return ToolResult.Fail($"File not found: {path}");

        var info = new FileInfo(path);
        if (info.Length > 5 * 1024 * 1024)
            return ToolResult.Fail($"File too large ({info.Length / 1024}KB). Max 5MB.");

        var bytes = File.ReadAllBytes(path);
        var b64 = Convert.ToBase64String(bytes);
        if (b64.Length > 10000)
            return ToolResult.Ok($"Base64 ({b64.Length} chars, first 500):\n{b64[..500]}...");
        return ToolResult.Ok(b64);
    }
}
