#if UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX || UNITY_IOS
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using AOT;

namespace Aidlab.BLE
{
    public class AppleBLEConnector : IBleConnector
    {
        // Native callbacks carry the id of their connector, so a callback that arrives after Disconnect finds none.
        private static readonly Dictionary<int, AppleBLEConnector> connectors = new Dictionary<int, AppleBLEConnector>();
        private static int nextId;

        private readonly AidlabSDK aidlabSdk;
        private readonly string targetName;
        private readonly string targetAddress;
        private readonly int id;
        private readonly IntPtr native;

        // The peripheral identifier this connector holds in AidlabSDK from accepting its discovery until Disconnect.
        private readonly object deviceLock = new object();
        private string heldDevice;
        private volatile bool disposed;

        private volatile bool isConnected;
        private volatile bool firmwareReceived;
        private volatile bool timeSetConfirmed;
        private volatile bool timeSetAttempted;
        private volatile bool timeSetFailed;
        private int connectedAtTick = -1;

        private readonly Queue<byte[]> writeQueue = new Queue<byte[]>();
        private readonly AutoResetEvent writeSignal = new AutoResetEvent(false);
        private readonly Thread writerThread;
        private volatile bool writerRunning = true;

        public bool IsConnected => isConnected;
        public bool HasFirmwareRevision => firmwareReceived;

        private static readonly AppleBLEApi.DataCallback DataCallback = OnData;
        private static readonly AppleBLEApi.EventCallback EventCallback = OnEvent;
        private static readonly AppleBLEApi.DiscoveryCallback DiscoveryCallback = OnDiscovered;

        public AppleBLEConnector(AidlabSDK aidlabSdk, string deviceNameToConnect, string deviceAddressToConnect)
        {
            this.aidlabSdk = aidlabSdk;
            targetName = deviceNameToConnect ?? "";
            targetAddress = deviceAddressToConnect ?? "";

            lock (connectors)
            {
                id = ++nextId;
                connectors[id] = this;
            }
            native = AppleBLEApi.Create(new IntPtr(id), DataCallback, EventCallback, DiscoveryCallback);

            writerThread = new Thread(WriterLoop);
            writerThread.IsBackground = true;
            writerThread.Start();
        }

        public void ConnectionProcess()
        {
            MaybeNotifyConnectedAfterTimeout();
        }

        public void Disconnect()
        {
            lock (deviceLock)
            {
                if (disposed)
                    return;
                disposed = true;
                if (heldDevice != null)
                    AidlabSDK.ReleaseDevice(heldDevice);
            }
            isConnected = false;
            lock (connectors)
            {
                connectors.Remove(id);
            }
            writerRunning = false;
            writeSignal.Set();
            // The writer calls into the native manager, which Destroy frees.
            writerThread.Join();
            AppleBLEApi.Destroy(native);
        }

        private static AppleBLEConnector Find(IntPtr context)
        {
            lock (connectors)
            {
                connectors.TryGetValue(context.ToInt32(), out AppleBLEConnector connector);
                return connector;
            }
        }

        public void Write(byte[] payload)
        {
            if (payload == null || payload.Length == 0)
                return;

            lock (writeQueue)
            {
                writeQueue.Enqueue(payload);
            }
            writeSignal.Set();
        }

        private void WriterLoop()
        {
            while (writerRunning)
            {
                writeSignal.WaitOne();

                while (true)
                {
                    byte[] payload = null;
                    lock (writeQueue)
                    {
                        if (writeQueue.Count > 0)
                            payload = writeQueue.Dequeue();
                    }

                    if (payload == null)
                        break;

                    if (!isConnected)
                        continue;

                    SendChunked(payload);
                }
            }
        }

        private void SendChunked(byte[] payload)
        {
            int chunkSize = 20;
            if (aidlabSdk.UsesV4Protocol())
            {
                int max = AppleBLEApi.GetMaxWriteLength(native);
                if (max > 0)
                    chunkSize = Math.Min(max, 512);
            }

            int offset = 0;
            int chunkIndex = 0;
            while (offset < payload.Length)
            {
                int size = Math.Min(chunkSize, payload.Length - offset);
                byte[] chunk = payload;
                if (size < payload.Length)
                {
                    chunk = new byte[size];
                    Buffer.BlockCopy(payload, offset, chunk, 0, size);
                }
                bool ok = AppleBLEApi.Write(native, chunk, size);
                chunkIndex++;
                if (!ok)
                {
                    lock (writeQueue)
                    {
                        writeQueue.Clear();
                    }
                    writerRunning = false;
                    aidlabSdk.OnTransportFailure(
                        $"AppleBLEConnector: Write failed (chunk #{chunkIndex}, {size}B)", this);
                    return;
                }
                offset += size;
            }
            aidlabSdk.OnTransportFrameWritten(payload);
        }

        // Runs on the CoreBluetooth queue and decides whether the native manager connects to the peripheral.
        [MonoPInvokeCallback(typeof(AppleBLEApi.DiscoveryCallback))]
        private static bool OnDiscovered(IntPtr context, IntPtr identifierPtr, IntPtr namePtr)
        {
            AppleBLEConnector instance = Find(context);
            if (instance == null)
                return false;

            string identifier = Marshal.PtrToStringAnsi(identifierPtr);
            bool isTarget = instance.targetAddress.Length == 0
                ? AidlabSDK.MatchesTargetName(Marshal.PtrToStringAnsi(namePtr), instance.targetName)
                : string.Equals(identifier, instance.targetAddress, StringComparison.OrdinalIgnoreCase);
            if (!isTarget)
                return false;

            lock (instance.deviceLock)
            {
                if (instance.disposed || !AidlabSDK.TryHoldDevice(identifier))
                    return false;
                instance.heldDevice = identifier;
                return true;
            }
        }

        [MonoPInvokeCallback(typeof(AppleBLEApi.DataCallback))]
        private static void OnData(IntPtr context, IntPtr data, int size)
        {
            AppleBLEConnector instance = Find(context);
            if (instance == null)
                return;

            if (data == IntPtr.Zero || size <= 0)
                return;

            // Don't feed any bytes into the C++ core until we know device time was set.
            // Otherwise we can ingest sessions created under the default RTC epoch (1971) and poison SessionProcessor.
            if (!instance.timeSetConfirmed)
                return;

            byte[] chunk = new byte[size];
            Marshal.Copy(data, chunk, 0, size);
            // On the CoreBluetooth queue, so that acknowledgements do not wait for a Unity frame.
            instance.aidlabSdk.OnAidlabDataReceived(chunk, chunk.Length);
        }

        [MonoPInvokeCallback(typeof(AppleBLEApi.EventCallback))]
        private static void OnEvent(IntPtr context, int evt, IntPtr messagePtr)
        {
            AppleBLEConnector instance = Find(context);
            if (instance == null)
                return;

            string message = messagePtr == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(messagePtr);
            switch (evt)
            {
                case 1: // connected
                    instance.isConnected = true;
                    instance.connectedAtTick = Environment.TickCount;
                    instance.timeSetConfirmed = false;
                    instance.timeSetAttempted = false;
                    instance.timeSetFailed = false;
                    if (instance.firmwareReceived)
                        instance.MaybeNotifyConnected();
                    break;
                case 2: // disconnected
                    instance.isConnected = false;
                    instance.OnMainThread(instance.aidlabSdk.OnAidlabDisconnected);
                    break;
                case 3: // firmware
                    instance.aidlabSdk.firmwareRevisionStr = message;
                    instance.firmwareReceived = true;
                    if (instance.isConnected)
                        instance.MaybeNotifyConnected();
                    break;
                case 4: // hardware
                    instance.aidlabSdk.hardwareRevisionStr = message;
                    break;
                case 5: // error
                    UnityEngine.Debug.LogWarning($"Aidlab BLE: {message}");
                    break;
                case 6: // current time written
                    instance.timeSetAttempted = true;
                    break;
                case 7: // current time confirmed
                    instance.timeSetConfirmed = true;
                    if (instance.isConnected && instance.firmwareReceived)
                        instance.MaybeNotifyConnected();
                    break;
                case 8: // current time failed
                    // Don't proceed; without time, v3/v4 session timestamps may be invalid (1971).
                    instance.timeSetFailed = true;
                    break;
            }
        }

        private void MaybeNotifyConnected()
        {
            // Python sets time (2A2B) before starting collect; do the same when possible.
            // If time isn't available on a given device/firmware, we'll fall back after a short timeout.
            if (!timeSetConfirmed)
                return;

            NotifyConnected();
        }

        private void NotifyConnected()
        {
            OnMainThread(() =>
            {
                aidlabSdk.DeviceAddress = heldDevice;
                aidlabSdk.OnAidlabConnected();
            });
        }

        private void MaybeNotifyConnectedAfterTimeout()
        {
            if (!isConnected || !firmwareReceived || timeSetConfirmed || timeSetFailed)
                return;

            if (connectedAtTick < 0)
                return;

            int elapsedMs = unchecked(Environment.TickCount - connectedAtTick);
            // If we attempted to set time (CTS present), be strict: don't proceed without confirmation.
            // Proceeding would ingest sessions timestamped with the default RTC epoch (1971) and break sync.
            if (timeSetAttempted)
            {
                if (elapsedMs < 10000)
                    return;

                timeSetFailed = true;
                UnityEngine.Debug.LogWarning("Aidlab BLE: time set not confirmed within 10s; disconnecting");
                // Disconnects this connector too.
                OnMainThread(aidlabSdk.OnAidlabDisconnected);
                return;
            }

            if (elapsedMs < 2000)
                return;

            // No CTS on this device/firmware - allow higher layers to proceed.
            timeSetConfirmed = true;
            UnityEngine.Debug.LogWarning("Aidlab BLE: time service not available; proceeding without set time");
            NotifyConnected();
        }

        // Runs action on the main thread unless this connector has been disconnected by then; AidlabSDK disconnects
        // a connector when it replaces it.
        private void OnMainThread(Action action)
        {
            AidlabSDK.EnqueueMainThreadEvent(() =>
            {
                if (!disposed)
                    action();
            });
        }
    }
}
#endif
