using Serilog;

namespace Hawkeye.VisionBuilder.Workflow.DataTransfer;

public class PythonModelProxyHTTP
{
    private static bool _isInitialized = false;
    private static DockerScriptRunner _pythonScriptRunner;
    private static CSharpDataTransferHTTP _cSharpDataTransferHTTP;

    static object _lock = new object();

    public static void Initialize()
    {
        lock (_lock)
        {
            if (_isInitialized) return;
            _isInitialized = true;

            var workDirAbsPath = Path.GetFullPath(@"..\Data\Models");
            _pythonScriptRunner = new DockerScriptRunner(workDirAbsPath);


            _pythonScriptRunner.Start();
            // Wait for the server to start by checking if port 8000 is open
            while (true)
            {
                try
                {
                    HttpClient http = new HttpClient();
                    // check if 404 occurs on localhost:8000
                    var response = http.GetAsync("http://127.0.0.1:8000/").Result;
                    if (response.StatusCode == System.Net.HttpStatusCode.NotFound ||
                        response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        break; // Port is open
                    }

                }
                catch
                {
                    Log.Debug("Waiting for port to open");
                    // Ignore exceptions and retry
                }

                Thread.Sleep(1000); // Wait before retrying
            }
            Thread.Sleep(2000);
            _cSharpDataTransferHTTP = new CSharpDataTransferHTTP();
        }
    }

    public static CSharpDataTransferHTTP GetInterface()
    {
        if (!_isInitialized) Initialize();

        return _cSharpDataTransferHTTP;
    }
}