using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using AxCopilot.SDK;

namespace AxCopilot.Handlers;

public class JsonHandler : IActionHandler
{
	private static readonly JsonSerializerOptions _prettyOpts = new JsonSerializerOptions
	{
		WriteIndented = true
	};

	private static readonly JsonSerializerOptions _compactOpts = new JsonSerializerOptions
	{
		WriteIndented = false
	};

	public string? Prefix => "json";

	public PluginMetadata Metadata => new PluginMetadata("JsonFormatter", "JSON 검증/포맷 — json 뒤에 내용 또는 명령 입력", "1.0", "AX");

	public Task<IEnumerable<LauncherItem>> GetItemsAsync(string query, CancellationToken ct)
	{
		string text = query.Trim();
		if (string.IsNullOrWhiteSpace(text) || text.Equals("format", StringComparison.OrdinalIgnoreCase) || text.Equals("minify", StringComparison.OrdinalIgnoreCase) || text.Equals("min", StringComparison.OrdinalIgnoreCase))
		{
			string text2 = "";
			try
			{
				text2 = Clipboard.GetText();
			}
			catch
			{
			}
			if (string.IsNullOrWhiteSpace(text2))
			{
				return Task.FromResult((IEnumerable<LauncherItem>)new _003C_003Ez__ReadOnlySingleElementList<LauncherItem>(new LauncherItem("클립보드가 비어 있습니다", "클립보드에 JSON 텍스트를 복사한 뒤 실행하세요", null, null, null, "\ue77f")));
			}
			return Task.FromResult(BuildItems(text2, text.StartsWith("min", StringComparison.OrdinalIgnoreCase)));
		}
		return Task.FromResult(BuildItems(text, isMinify: false));
	}

	private static IEnumerable<LauncherItem> BuildItems(string input, bool isMinify)
	{
		try
		{
			using JsonDocument jsonDocument = JsonDocument.Parse(input, new JsonDocumentOptions
			{
				AllowTrailingCommas = true,
				CommentHandling = JsonCommentHandling.Skip
			});
			string text = JsonSerializer.Serialize(jsonDocument.RootElement, _prettyOpts);
			string text2 = JsonSerializer.Serialize(jsonDocument.RootElement, _compactOpts);
			JsonValueKind valueKind = jsonDocument.RootElement.ValueKind;
			if (1 == 0)
			{
			}
			string text3 = valueKind switch
			{
				JsonValueKind.Object => $"Object ({jsonDocument.RootElement.EnumerateObject().Count()}개 키)", 
				JsonValueKind.Array => $"Array ({jsonDocument.RootElement.GetArrayLength()}개 항목)", 
				_ => jsonDocument.RootElement.ValueKind.ToString(), 
			};
			if (1 == 0)
			{
			}
			string text4 = text3;
			string data = (isMinify ? text2 : text);
			string text5 = (isMinify ? "미니파이" : "포맷");
			string text6 = ((text2.Length > 100) ? (text2.Substring(0, 97) + "…") : text2);
			return new _003C_003Ez__ReadOnlyArray<LauncherItem>(new LauncherItem[3]
			{
				new LauncherItem("✅ 유효한 JSON — " + text4, text6 + "  ·  Enter로 " + text5 + " 결과 클립보드 복사", null, data, null, "\ue930"),
				new LauncherItem("포맷 (Pretty Print) 복사", $"{text.Length}자  ·  들여쓰기 2스페이스", null, text, null, "\ue8a4"),
				new LauncherItem("미니파이 (Minify) 복사", $"{text2.Length}자  ·  공백 제거", null, text2, null, "\ue8c6")
			});
		}
		catch (JsonException ex)
		{
			string subtitle = ((ex.Message.Length > 100) ? (ex.Message.Substring(0, 97) + "…") : ex.Message);
			return new _003C_003Ez__ReadOnlySingleElementList<LauncherItem>(new LauncherItem("❌ JSON 오류", subtitle, null, null, null, "\uea39"));
		}
	}

	public Task ExecuteAsync(LauncherItem item, CancellationToken ct)
	{
		if (item.Data is string text)
		{
			try
			{
				Clipboard.SetText(text);
			}
			catch
			{
			}
		}
		return Task.CompletedTask;
	}
}
