using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;

class Launcher
{
    [STAThread]
    static void Main()
    {
        // 1. Get a free port
        int port = GetFreePort();

        // 2. Resolve server paths
        string appDir = AppDomain.CurrentDomain.BaseDirectory;
        string serverJs = Path.Combine(appDir, "server.js");

        if (!File.Exists(serverJs))
        {
            serverJs = Path.Combine(Directory.GetCurrentDirectory(), "server.js");
            appDir = Directory.GetCurrentDirectory();
        }

        if (!File.Exists(serverJs))
        {
            MessageBox.Show("server.js not found in current directory. Please make sure the server files are located next to this executable.", "Error");
            return;
        }

        // 3. Find Antigravity.exe node engine
        string antigravityExe = @"C:\Users\Dell\AppData\Local\Programs\antigravity\Antigravity.exe";
        if (!File.Exists(antigravityExe))
        {
            string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            antigravityExe = Path.Combine(userProfile, @"AppData\Local\Programs\antigravity\Antigravity.exe");
        }

        // 4. Start Node Server process (hidden window)
        ProcessStartInfo serverStartInfo = new ProcessStartInfo();
        if (File.Exists(antigravityExe))
        {
            serverStartInfo.FileName = antigravityExe;
            serverStartInfo.Arguments = string.Format("\"{0}\" --port {1}", serverJs, port);
            serverStartInfo.EnvironmentVariables["ELECTRON_RUN_AS_NODE"] = "1";
            serverStartInfo.UseShellExecute = false;
        }
        else
        {
            // Fallback to agy-node command if in PATH
            serverStartInfo.FileName = "cmd.exe";
            serverStartInfo.Arguments = string.Format("/c agy-node \"{0}\" --port {1}", serverJs, port);
            serverStartInfo.UseShellExecute = false;
        }
        
        serverStartInfo.CreateNoWindow = true;
        serverStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        serverStartInfo.WorkingDirectory = appDir;

        try
        {
            Process.Start(serverStartInfo);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Failed to start background server: " + ex.Message, "Error");
            return;
        }

        // Wait a short moment for the server to spin up and bind the socket
        System.Threading.Thread.Sleep(800);

        // 5. Open Edge in App Mode
        string edgePath = @"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe";
        if (!File.Exists(edgePath))
        {
            try
            {
                Process.Start(string.Format("http://localhost:{0}", port));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to open web browser: " + ex.Message, "Error");
            }
        }
        else
        {
            try
            {
                ProcessStartInfo edgeStartInfo = new ProcessStartInfo();
                edgeStartInfo.FileName = edgePath;
                edgeStartInfo.Arguments = string.Format("--app=http://localhost:{0}", port);
                Process.Start(edgeStartInfo);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to launch Edge App Mode: " + ex.Message, "Error");
            }
        }
    }

    static int GetFreePort()
    {
        try
        {
            TcpListener l = new TcpListener(IPAddress.Loopback, 0);
            l.Start();
            int port = ((IPEndPoint)l.LocalEndpoint).Port;
            l.Stop();
            return port;
        }
        catch
        {
            // Fallback to default port if listener fails
            return 3000;
        }
    }
}
