using System.IO;
using System.Text.Json;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace AxCopilot.Services.Agent;

/// <summary>
/// Word (.docx) 문서를 생성하는 내장 스킬.
/// 테이블, 텍스트 스타일링, 머리글/바닥글, 페이지 나누기 등 고급 기능을 지원합니다.
/// </summary>
public partial class DocxSkill : IAgentTool
{
    public string Name => "docx_create";
    public string Description => "Create a rich Word (.docx) document. " +
        "Supports: sections with heading+body, tables with optional header styling, " +
        "text formatting (bold, italic, color, highlight, shading), " +
        "headers/footers with page numbers, page breaks between sections, " +
        "and numbered/bulleted lists.";

    public ToolParameterSchema Parameters => new()
    {
        Properties = new()
        {
            ["path"] = new() { Type = "string", Description = "Output file path (.docx). Relative to work folder." },
            ["title"] = new() { Type = "string", Description = "Document title (optional)." },
            ["sections"] = new()
            {
                Type = "array",
                Description = "Array of content blocks. Each block is one of:\n" +
                    "• Section: {\"heading\": \"...\", \"body\": \"...\", \"level\": 1|2}\n" +
                    "• Table: {\"type\": \"table\", \"headers\": [\"A\",\"B\"], \"rows\": [[\"1\",\"2\"]], \"style\": \"striped|plain\"}\n" +
                    "• PageBreak: {\"type\": \"pagebreak\"}\n" +
                    "• List: {\"type\": \"list\", \"style\": \"bullet|number\", \"items\": [\"item1\", \"item2\"]}\n" +
                    "Body text supports inline formatting: **bold**, *italic*, `code`.",
                Items = new() { Type = "object" }
            },
            ["header"] = new() { Type = "string", Description = "Header text shown at top of every page (optional)." },
            ["footer"] = new() { Type = "string", Description = "Footer text. Use {page} for page number. Default: 'AX Copilot · {page}' if header is set." },
            ["page_numbers"] = new() { Type = "boolean", Description = "Show page numbers in footer. Default: true if header or footer is set." },
        },
        Required = ["path", "sections"]
    };

    public async Task<ToolResult> ExecuteAsync(JsonElement args, AgentContext context, CancellationToken ct)
    {
        var path = args.GetProperty("path").GetString() ?? "";
        var title = args.TryGetProperty("title", out var t) ? t.GetString() ?? "" : "";
        var headerText = args.TryGetProperty("header", out var hdr) ? hdr.GetString() : null;
        var footerText = args.TryGetProperty("footer", out var ftr) ? ftr.GetString() : null;
        var showPageNumbers = args.TryGetProperty("page_numbers", out var pn) ? pn.GetBoolean() :
            (headerText != null || footerText != null);

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

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

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

        try
        {
            var sections = args.GetProperty("sections");

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

            using var doc = WordprocessingDocument.Create(fullPath, WordprocessingDocumentType.Document);
            var mainPart = doc.AddMainDocumentPart();
            mainPart.Document = new Document();
            var body = mainPart.Document.AppendChild(new Body());

            // 머리글/바닥글 설정
            if (headerText != null || footerText != null || showPageNumbers)
                AddHeaderFooter(mainPart, body, headerText, footerText, showPageNumbers);

            // 제목
            if (!string.IsNullOrEmpty(title))
            {
                body.Append(CreateTitleParagraph(title));
                // 제목 아래 구분선
                body.Append(new Paragraph(
                    new ParagraphProperties
                    {
                        ParagraphBorders = new ParagraphBorders(
                            new BottomBorder { Val = BorderValues.Single, Size = 6, Color = "4472C4", Space = 1 }),
                        SpacingBetweenLines = new SpacingBetweenLines { After = "300" },
                    }));
            }

            int sectionCount = 0;
            int tableCount = 0;
            foreach (var section in sections.EnumerateArray())
            {
                var blockType = section.TryGetProperty("type", out var bt) ? bt.GetString()?.ToLower() : null;

                if (blockType == "pagebreak")
                {
                    body.Append(CreatePageBreak());
                    continue;
                }

                if (blockType == "table")
                {
                    body.Append(CreateTable(section));
                    tableCount++;
                    continue;
                }

                if (blockType == "list")
                {
                    AppendList(body, section);
                    continue;
                }

                // 일반 섹션 (heading + body)
                var heading = section.TryGetProperty("heading", out var h) ? h.GetString() ?? "" : "";
                var bodyText = section.TryGetProperty("body", out var b) ? b.GetString() ?? "" : "";
                var level = section.TryGetProperty("level", out var lv) ? lv.GetInt32() : 1;

                if (!string.IsNullOrEmpty(heading))
                    body.Append(CreateHeadingParagraph(heading, level));

                if (!string.IsNullOrEmpty(bodyText))
                {
                    foreach (var line in bodyText.Split('\n'))
                    {
                        body.Append(CreateBodyParagraph(line));
                    }
                }
                sectionCount++;
            }

            mainPart.Document.Save();

            var parts = new List<string>();
            if (!string.IsNullOrEmpty(title)) parts.Add($"제목: {title}");
            if (sectionCount > 0) parts.Add($"섹션: {sectionCount}개");
            if (tableCount > 0) parts.Add($"테이블: {tableCount}개");
            if (headerText != null) parts.Add("머리글");
            if (showPageNumbers) parts.Add("페이지번호");

            return ToolResult.Ok(
                $"Word 문서 생성 완료: {fullPath}\n{string.Join(", ", parts)}",
                fullPath);
        }
        catch (Exception ex)
        {
            return ToolResult.Fail($"Word 문서 생성 실패: {ex.Message}");
        }
    }

}
