using System;
using System.Diagnostics;
using Microsoft.Win32;

namespace AxCopilot.Services;

public static class ShellExtensionService
{
	private const string MenuKey = "AxCopilotShell";

	private const string MenuLabel = "AX Agent로 분석";

	public static bool Register()
	{
		try
		{
			string text = Process.GetCurrentProcess().MainModule?.FileName ?? "";
			if (string.IsNullOrEmpty(text))
			{
				return false;
			}
			RegisterContextMenu("Software\\Classes\\*\\shell", text, "--analyze-file \"%1\"");
			RegisterContextMenu("Software\\Classes\\Directory\\shell", text, "--analyze-folder \"%1\"");
			RegisterContextMenu("Software\\Classes\\Directory\\Background\\shell", text, "--analyze-folder \"%V\"");
			LogService.Info("셸 확장 등록 완료");
			return true;
		}
		catch (Exception ex)
		{
			LogService.Error("셸 확장 등록 실패: " + ex.Message);
			return false;
		}
	}

	public static bool Unregister()
	{
		try
		{
			DeleteKey("Software\\Classes\\*\\shell\\AxCopilotShell");
			DeleteKey("Software\\Classes\\Directory\\shell\\AxCopilotShell");
			DeleteKey("Software\\Classes\\Directory\\Background\\shell\\AxCopilotShell");
			LogService.Info("셸 확장 해제 완료");
			return true;
		}
		catch (Exception ex)
		{
			LogService.Error("셸 확장 해제 실패: " + ex.Message);
			return false;
		}
	}

	public static bool IsRegistered()
	{
		try
		{
			using RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("Software\\Classes\\*\\shell\\AxCopilotShell");
			return registryKey != null;
		}
		catch
		{
			return false;
		}
	}

	private static void RegisterContextMenu(string basePath, string exePath, string args)
	{
		string text = basePath + "\\AxCopilotShell";
		using RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(text);
		if (registryKey == null)
		{
			return;
		}
		registryKey.SetValue("", "AX Agent로 분석");
		registryKey.SetValue("Icon", "\"" + exePath + "\",0");
		using RegistryKey registryKey2 = Registry.CurrentUser.CreateSubKey(text + "\\command");
		registryKey2?.SetValue("", "\"" + exePath + "\" " + args);
	}

	private static void DeleteKey(string path)
	{
		try
		{
			Registry.CurrentUser.DeleteSubKeyTree(path, throwOnMissingSubKey: false);
		}
		catch
		{
		}
	}

	public static (string Action, string Path)? ParseCommandLine(string[] args)
	{
		for (int i = 0; i < args.Length - 1; i++)
		{
			if (args[i] == "--analyze-file")
			{
				return ("file", args[i + 1]);
			}
			if (args[i] == "--analyze-folder")
			{
				return ("folder", args[i + 1]);
			}
		}
		return null;
	}
}
