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

namespace AxCopilot.Handlers;

public class JournalHandler : IActionHandler
{
	public string? Prefix => "journal";

	public PluginMetadata Metadata => new PluginMetadata("Journal", "업무 일지 자동 생성 — journal", "1.0", "AX");

	public Task<IEnumerable<LauncherItem>> GetItemsAsync(string query, CancellationToken ct)
	{
		string text = query.Trim();
		DateTime targetDate;
		if (string.IsNullOrWhiteSpace(text))
		{
			targetDate = DateTime.Today;
		}
		else
		{
			if (!DateTime.TryParse(text, out var result))
			{
				return Task.FromResult((IEnumerable<LauncherItem>)new _003C_003Ez__ReadOnlySingleElementList<LauncherItem>(new LauncherItem("날짜 형식 오류", "예: journal 2026-03-25 또는 journal (오늘)", null, null, null, "\ue7ba")));
			}
			targetDate = result.Date;
		}
		int days = (DateTime.Today - targetDate).Days;
		List<DailyUsageStats> stats = UsageStatisticsService.GetStats(Math.Max(days + 1, 1));
		DailyUsageStats dailyUsageStats = stats.FirstOrDefault((DailyUsageStats s) => s.Date == targetDate.ToString("yyyy-MM-dd"));
		List<LauncherItem> list = new List<LauncherItem>();
		if (dailyUsageStats == null)
		{
			list.Add(new LauncherItem($"{targetDate:yyyy-MM-dd} — 기록 없음", "해당 날짜의 사용 기록이 없습니다", null, null, null, "\ue946"));
			return Task.FromResult((IEnumerable<LauncherItem>)list);
		}
		double value = (double)dailyUsageStats.ActiveSeconds / 3600.0;
		StringBuilder stringBuilder = new StringBuilder();
		StringBuilder stringBuilder2 = stringBuilder;
		StringBuilder stringBuilder3 = stringBuilder2;
		StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(14, 2, stringBuilder2);
		handler.AppendLiteral("## 업무 일지 — ");
		handler.AppendFormatted(targetDate, "yyyy-MM-dd");
		handler.AppendLiteral(" (");
		handler.AppendFormatted(targetDate, "dddd");
		handler.AppendLiteral(")");
		stringBuilder3.AppendLine(ref handler);
		stringBuilder.AppendLine();
		stringBuilder2 = stringBuilder;
		StringBuilder stringBuilder4 = stringBuilder2;
		handler = new StringBuilder.AppendInterpolatedStringHandler(18, 1, stringBuilder2);
		handler.AppendLiteral("- **PC 활성 시간**: ");
		handler.AppendFormatted(value, "F1");
		handler.AppendLiteral("시간");
		stringBuilder4.AppendLine(ref handler);
		stringBuilder2 = stringBuilder;
		StringBuilder stringBuilder5 = stringBuilder2;
		handler = new StringBuilder.AppendInterpolatedStringHandler(14, 1, stringBuilder2);
		handler.AppendLiteral("- **런처 호출**: ");
		handler.AppendFormatted(dailyUsageStats.LauncherOpens);
		handler.AppendLiteral("회");
		stringBuilder5.AppendLine(ref handler);
		if (dailyUsageStats.CommandUsage.Count > 0)
		{
			stringBuilder.AppendLine();
			stringBuilder.AppendLine("### 사용한 명령어");
			foreach (KeyValuePair<string, int> item in dailyUsageStats.CommandUsage.OrderByDescending<KeyValuePair<string, int>, int>((KeyValuePair<string, int> x) => x.Value).Take(10))
			{
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder6 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(8, 2, stringBuilder2);
				handler.AppendLiteral("- `");
				handler.AppendFormatted(item.Key);
				handler.AppendLiteral("` — ");
				handler.AppendFormatted(item.Value);
				handler.AppendLiteral("회");
				stringBuilder6.AppendLine(ref handler);
			}
		}
		stringBuilder.AppendLine();
		stringBuilder.AppendLine("---");
		stringBuilder2 = stringBuilder;
		StringBuilder stringBuilder7 = stringBuilder2;
		handler = new StringBuilder.AppendInterpolatedStringHandler(21, 1, stringBuilder2);
		handler.AppendLiteral("*AX Copilot 자동 생성 · ");
		handler.AppendFormatted(DateTime.Now, "HH:mm");
		handler.AppendLiteral("*");
		stringBuilder7.AppendLine(ref handler);
		string data = stringBuilder.ToString();
		IEnumerable<string> values = from x in dailyUsageStats.CommandUsage.OrderByDescending<KeyValuePair<string, int>, int>((KeyValuePair<string, int> x) => x.Value).Take(3)
			select x.Key;
		string value2 = ((dailyUsageStats.CommandUsage.Count > 0) ? ("주요 명령: " + string.Join(", ", values)) : "명령어 사용 기록 없음");
		list.Add(new LauncherItem($"{targetDate:yyyy-MM-dd} 업무 일지 — 클립보드로 복사", $"활성 {value:F1}h · 런처 {dailyUsageStats.LauncherOpens}회 · {value2}", null, data, null, "\ue70b"));
		list.Add(new LauncherItem($"PC 활성 시간: {value:F1}시간", "잠금 해제 시간 기준 누적", null, $"PC 활성 시간: {value:F1}시간", null, "\ue823"));
		list.Add(new LauncherItem($"런처 호출: {dailyUsageStats.LauncherOpens}회", "Alt+Space 또는 트레이 클릭", null, $"런처 호출: {dailyUsageStats.LauncherOpens}회", null, "\ue721"));
		if (dailyUsageStats.CommandUsage.Count > 0)
		{
			foreach (KeyValuePair<string, int> item2 in dailyUsageStats.CommandUsage.OrderByDescending<KeyValuePair<string, int>, int>((KeyValuePair<string, int> x) => x.Value).Take(5))
			{
				list.Add(new LauncherItem($"{item2.Key} — {item2.Value}회", "Enter로 복사", null, $"{item2.Key}: {item2.Value}회", null, "\ue756"));
			}
		}
		return Task.FromResult((IEnumerable<LauncherItem>)list);
	}

	public Task ExecuteAsync(LauncherItem item, CancellationToken ct)
	{
		object data = item.Data;
		string text = data as string;
		if (text != null && !string.IsNullOrWhiteSpace(text))
		{
			try
			{
				Application current = Application.Current;
				if (current != null)
				{
					((DispatcherObject)current).Dispatcher.Invoke((Action)delegate
					{
						Clipboard.SetText(text);
					});
				}
			}
			catch
			{
			}
			NotificationService.Notify("업무 일지", "클립보드에 복사되었습니다");
		}
		return Task.CompletedTask;
	}
}
