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

namespace AxCopilot.Services.Agent;

/// <summary>
/// Markdown (.md) 문서를 생성하는 내장 스킬.
/// LLM이 마크다운 내용을 전달하면 파일로 저장합니다.
/// </summary>
public class MarkdownSkill : IAgentTool
{
    public string Name => "markdown_create";
    public string Description => "Create a Markdown (.md) document file. Provide the content in Markdown format.";

    public ToolParameterSchema Parameters => new()
    {
        Properties = new()
        {
            ["path"] = new() { Type = "string", Description = "Output file path (.md). Relative to work folder." },
            ["content"] = new() { Type = "string", Description = "Markdown content to write" },
            ["title"] = new() { Type = "string", Description = "Optional document title. If provided, prepends '# title' at the top." },
        },
        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 title = args.TryGetProperty("title", out var t) ? t.GetString() : null;

        var fullPath = FileReadTool.ResolvePath(path, context.WorkFolder);
        if (context.ActiveTab == "Cowork") fullPath = AgentContext.EnsureTimestampedPath(fullPath);
        if (!fullPath.EndsWith(".md", StringComparison.OrdinalIgnoreCase))
            fullPath += ".md";

        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);

            var sb = new StringBuilder();
            if (!string.IsNullOrEmpty(title))
            {
                sb.AppendLine($"# {title}");
                sb.AppendLine();
            }
            sb.Append(content);

            await File.WriteAllTextAsync(fullPath, sb.ToString(), Encoding.UTF8, ct);

            var lines = sb.ToString().Split('\n').Length;
            return ToolResult.Ok(
                $"Markdown 문서 저장 완료: {fullPath} ({lines} lines)",
                fullPath);
        }
        catch (Exception ex)
        {
            return ToolResult.Fail($"Markdown 저장 실패: {ex.Message}");
        }
    }
}
