using System;
using System.Threading;
using System.Windows.Forms;
using AutoIngest.Core;

namespace AutoIngest.App
{
    static class Program
    {
        static Mutex _mutex = null!;

        [STAThread]
        static void Main()
        {
            bool owned;
            _mutex = new Mutex(true, "AutoIngest_SingleInstance", out owned);
            if (!owned)
            {
                MessageBox.Show(
                    "AutoIngest is already running.",
                    "Already Running",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
                return;
            }

            // Wire unhandled-exception handlers BEFORE Application.Run so a crash still leaves a
            // forensic trail in the file log. Without this, a fatal exception shows only the
            // generic "AutoIngest has stopped working" dialog and zero diagnostic record.
            AppDomain.CurrentDomain.UnhandledException += (_, e) =>
            {
                if (e.ExceptionObject is Exception ex)
                    FileLogger.LogException("AppDomain unhandled exception", ex);
            };
            Application.ThreadException += (_, e) =>
            {
                FileLogger.LogException("UI thread unhandled exception", e.Exception);
            };
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.SetHighDpiMode(HighDpiMode.SystemAware);

            // MainForm starts hidden — it lives in the tray and only pops up as a toast
            // when an SD card / USB import is in progress.
            Application.Run(new MainForm());
        }
    }
}
