using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using MRCC.Launcher;

internal static class Program
{
    public static bool IsDevMode;
    private static readonly object _logLock = new();
    private static readonly string LogPath = "redcircuit.log";

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool AllocConsole();

    [STAThread]
    public static void Main(string[] args)
    {
        IsDevMode = args.Any(a => string.Equals(a, "dev", StringComparison.OrdinalIgnoreCase));

        if (IsDevMode)
        {
            AllocConsole();
            Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true });
            Log("=== RedCircuit 开发模式 ===");
            Log($"工作目录: {Environment.CurrentDirectory}");
            Log($"EXE目录: {AppContext.BaseDirectory}");
            Log("HTML5 世界直接运行于 WebView2 内，控制台用于查看日志。");
        }

        // 启动器 UI：WebView2 加载 HTML5 世界
        var app = new App();
        app.Run(new MainWindow());
    }

    public static void Log(string message)
    {
        var line = $"[{DateTime.Now:HH:mm:ss.fff}] {message}";
        lock (_logLock)
        {
            if (IsDevMode) Console.WriteLine(line);
            Debug.WriteLine(line);
            try { File.AppendAllText(LogPath, line + Environment.NewLine, Encoding.UTF8); } catch { }
        }
    }
}
