using System.Windows;
using AxCopilot.Models;
using AxCopilot.Services;

namespace AxCopilot.Views;

public partial class ChatWindow
{
    // ─── 대화 분기 (Fork) ──────────────────────────────────────────────

    private void ForkConversation(ChatConversation source, int atIndex)
    {
        var branchCount = _storage.LoadAllMeta()
            .Count(m => m.ParentId == source.Id) + 1;

        var fork = new ChatConversation
        {
            Title = $"{source.Title} (분기 {branchCount})",
            Tab = source.Tab,
            Category = source.Category,
            WorkFolder = source.WorkFolder,
            SystemCommand = source.SystemCommand,
            ParentId = source.Id,
            BranchLabel = $"분기 {branchCount}",
            BranchAtIndex = atIndex,
        };

        // 분기 시점까지의 메시지 복제
        for (int i = 0; i <= atIndex && i < source.Messages.Count; i++)
        {
            var m = source.Messages[i];
            fork.Messages.Add(new ChatMessage
            {
                Role = m.Role,
                Content = m.Content,
                Timestamp = m.Timestamp,
            });
        }

        try
        {
            _storage.Save(fork);
            ShowToast($"분기 생성: {fork.Title}");

            // 분기 대화로 전환
            lock (_convLock) _currentConversation = fork;
            ChatTitle.Text = fork.Title;
            RenderMessages();
            RefreshConversationList();
        }
        catch (Exception ex)
        {
            ShowToast($"분기 실패: {ex.Message}", "\uE783");
        }
    }

    // ─── 커맨드 팔레트 ─────────────────────────────────────────────────

    private void OpenCommandPalette()
    {
        var palette = new CommandPaletteWindow(ExecuteCommand) { Owner = this };
        palette.ShowDialog();
    }

    private void ExecuteCommand(string commandId)
    {
        switch (commandId)
        {
            case "tab:chat": TabChat.IsChecked = true; break;
            case "tab:cowork": TabCowork.IsChecked = true; break;
            case "tab:code": if (TabCode.IsEnabled) TabCode.IsChecked = true; break;
            case "new_conversation": StartNewConversation(); break;
            case "search_conversation": ToggleMessageSearch(); break;
            case "change_model": BtnModelSelector_Click(this, new RoutedEventArgs()); break;
            case "open_settings": BtnSettings_Click(this, new RoutedEventArgs()); break;
            case "open_statistics": new StatisticsWindow().Show(); break;
            case "change_folder": FolderPathLabel_Click(FolderPathLabel, null!); break;
            case "toggle_devmode":
                var llm = Llm;
                llm.DevMode = !llm.DevMode;
                _settings.Save();
                UpdateAnalyzerButtonVisibility();
                ShowToast(llm.DevMode ? "개발자 모드 켜짐" : "개발자 모드 꺼짐");
                break;
            case "open_audit_log":
                try { System.Diagnostics.Process.Start("explorer.exe", Services.AuditLogService.GetAuditFolder()); } catch (Exception) { /* 감사 로그 폴더 열기 실패 */ }
                break;
            case "paste_clipboard":
                try { var text = Clipboard.GetText(); if (!string.IsNullOrEmpty(text)) InputBox.Text += text; } catch (Exception) { /* 클립보드 접근 실패 */ }
                break;
            case "export_conversation": ExportConversation(); break;
        }
    }

    private void ExportConversation()
    {
        ChatConversation? conv;
        lock (_convLock) conv = _currentConversation;
        if (conv == null || conv.Messages.Count == 0) return;

        var dlg = new Microsoft.Win32.SaveFileDialog
        {
            FileName = $"{conv.Title}",
            DefaultExt = ".md",
            Filter = "Markdown (*.md)|*.md|JSON (*.json)|*.json|HTML (*.html)|*.html|PDF 인쇄용 HTML (*.pdf.html)|*.pdf.html|Text (*.txt)|*.txt"
        };
        if (dlg.ShowDialog() != true) return;

        var ext = System.IO.Path.GetExtension(dlg.FileName).ToLowerInvariant();
        string content;

        if (ext == ".json")
        {
            content = System.Text.Json.JsonSerializer.Serialize(conv, new System.Text.Json.JsonSerializerOptions
            {
                WriteIndented = true,
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            });
        }
        else if (dlg.FileName.EndsWith(".pdf.html"))
        {
            // PDF 인쇄용 HTML — 브라우저에서 자동으로 인쇄 대화상자 표시
            content = PdfExportService.BuildHtml(conv);
            System.IO.File.WriteAllText(dlg.FileName, content, System.Text.Encoding.UTF8);
            PdfExportService.OpenInBrowser(dlg.FileName);
            ShowToast("PDF 인쇄용 HTML이 생성되어 브라우저에서 열렸습니다");
            return;
        }
        else if (ext == ".html")
        {
            content = ExportToHtml(conv);
        }
        else
        {
            var sb = new System.Text.StringBuilder();
            sb.AppendLine($"# {conv.Title}");
            sb.AppendLine($"_생성: {conv.CreatedAt:yyyy-MM-dd HH:mm} · 주제: {conv.Category}_");
            sb.AppendLine();

            foreach (var msg in conv.Messages)
            {
                if (msg.Role == "system") continue;
                var label = msg.Role == "user" ? "**사용자**" : "**AI**";
                sb.AppendLine($"{label} ({msg.Timestamp:HH:mm})");
                sb.AppendLine();
                sb.AppendLine(msg.Content);
                if (msg.AttachedFiles is { Count: > 0 })
                {
                    sb.AppendLine();
                    sb.AppendLine("_첨부 파일: " + string.Join(", ", msg.AttachedFiles.Select(System.IO.Path.GetFileName)) + "_");
                }
                sb.AppendLine();
                sb.AppendLine("---");
                sb.AppendLine();
            }
            content = sb.ToString();
        }

        System.IO.File.WriteAllText(dlg.FileName, content, System.Text.Encoding.UTF8);
    }

    private static string ExportToHtml(ChatConversation conv)
    {
        var sb = new System.Text.StringBuilder();
        sb.AppendLine("<!DOCTYPE html><html><head><meta charset=\"utf-8\">");
        sb.AppendLine($"<title>{System.Net.WebUtility.HtmlEncode(conv.Title)}</title>");
        sb.AppendLine("<style>body{font-family:'Segoe UI',sans-serif;max-width:800px;margin:0 auto;padding:20px;background:#1a1a2e;color:#e0e0e0}");
        sb.AppendLine(".msg{margin:12px 0;padding:12px 16px;border-radius:12px}.user{background:#2d2d5e;margin-left:60px}.ai{background:#1e1e3a;margin-right:60px}");
        sb.AppendLine(".meta{font-size:11px;color:#888;margin-bottom:6px}.content{white-space:pre-wrap;line-height:1.6}");
        sb.AppendLine("h1{text-align:center;color:#8b6dff}pre{background:#111;padding:12px;border-radius:8px;overflow-x:auto}</style></head><body>");
        sb.AppendLine($"<h1>{System.Net.WebUtility.HtmlEncode(conv.Title)}</h1>");
        sb.AppendLine($"<p style='text-align:center;color:#888'>생성: {conv.CreatedAt:yyyy-MM-dd HH:mm} · 주제: {conv.Category}</p>");

        foreach (var msg in conv.Messages)
        {
            if (msg.Role == "system") continue;
            var cls = msg.Role == "user" ? "user" : "ai";
            var label = msg.Role == "user" ? "사용자" : "AI";
            sb.AppendLine($"<div class='msg {cls}'>");
            sb.AppendLine($"<div class='meta'>{label} · {msg.Timestamp:HH:mm}</div>");
            sb.AppendLine($"<div class='content'>{System.Net.WebUtility.HtmlEncode(msg.Content)}</div>");
            sb.AppendLine("</div>");
        }

        sb.AppendLine("</body></html>");
        return sb.ToString();
    }
}
