using Microsoft.Win32;
using AxCopilot.Services;

namespace AxCopilot;

public partial class App
{
    // ─── 자동 시작 / 앱 종료 헬퍼 ──────────────────────────────────────

    private static System.Drawing.Icon LoadAppIcon()
    {
        // DPI 인식 아이콘 크기 (기본 16 → 고DPI에서 20/24/32)
        var iconSize = System.Windows.Forms.SystemInformation.SmallIconSize;

        // 1) 파일 시스템에서 로드 (개발 환경)
        try
        {
            var exeDir = System.IO.Path.GetDirectoryName(Environment.ProcessPath)
                         ?? AppContext.BaseDirectory;
            var path = System.IO.Path.Combine(exeDir, "Assets", "icon.ico");
            if (System.IO.File.Exists(path))
                return new System.Drawing.Icon(path, iconSize);
        }
        catch (Exception) { }

        // 2) 내장 리소스에서 로드 (PublishSingleFile 배포)
        try
        {
            var uri = new Uri("pack://application:,,,/Assets/icon.ico");
            var stream = System.Windows.Application.GetResourceStream(uri)?.Stream;
            if (stream != null)
                return new System.Drawing.Icon(stream, iconSize);
        }
        catch (Exception) { }

        return System.Drawing.SystemIcons.Application;
    }

    private const string AutoRunKey  = @"Software\Microsoft\Windows\CurrentVersion\Run";
    private const string AutoRunName = "AxCopilot";

    private static bool IsAutoStartEnabled()
    {
        try
        {
            using var key = Registry.CurrentUser.OpenSubKey(AutoRunKey, writable: false);
            return key?.GetValue(AutoRunName) != null;
        }
        catch (Exception) { return false; }
    }

    private static void SetAutoStart(bool enable)
    {
        try
        {
            using var key = Registry.CurrentUser.OpenSubKey(AutoRunKey, writable: true);
            if (key == null) return;

            if (enable)
            {
                var exePath = Environment.ProcessPath
                    ?? System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName
                    ?? string.Empty;
                if (!string.IsNullOrEmpty(exePath))
                    key.SetValue(AutoRunName, $"\"{exePath}\"");
            }
            else
            {
                key.DeleteValue(AutoRunName, throwOnMissingValue: false);
            }
        }
        catch (Exception ex)
        {
            LogService.Warn($"자동 시작 레지스트리 설정 실패: {ex.Message}");
        }
    }

    protected override void OnExit(System.Windows.ExitEventArgs e)
    {
        _chatWindow?.ForceClose(); // 미리 생성된 ChatWindow 진짜 닫기
        _inputListener?.Dispose();
        _clipboardHistory?.Dispose();
        _indexService?.Dispose();
        _sessionTracking?.Dispose();
        _worktimeReminder?.Dispose();
        _trayIcon?.Dispose();
        try { _singleInstanceMutex?.ReleaseMutex(); } catch (Exception) { }
        _singleInstanceMutex?.Dispose();
        LogService.Info("=== AX Copilot 종료 ===");
        base.OnExit(e);
    }
}
