using UdonSharp;
using UnityEngine;
using VRC.SDK3.Video.Components.AVPro;
using VRC.SDKBase;
using VRC.SDK3.StringLoading;
using VRC.Udon.Common.Interfaces;
using System.Text;
using VRC.SDK3.Components.Video;

namespace Yamadev.YamachanWebUnit
{
    // ==========================================================================================================
    // DM Modified WebUnit v5.5 CANDIDATE (not reviewed, not a product file yet). v5.5 = v5.4 with two changes marked
    // "DM v5.5": the handles are marked as loading during a send (a stop then drops the request), and the request after
    // an unread one waits 5 s before it is handed over (bytes of the unread request stay on the server by position).
    // DM Modified WebUnit v5.4 (production variant) — personal use only, not for redistribution.
    // v5.4 = v5.2 with 11 transport players (A + DmExtraPlayers B..K), a reuse cooldown of 4.2 s (v5.2: 1.4 s),
    // DmRevision 6 and the code revision DmBuildRevision 6. The 11 bytes of a YouTube id therefore never reuse a
    // player inside one request (a reused player that was still opening its previous URL blocked the main thread for
    // up to about 1.3 s in v5.2). Real-client diagnostic (3B, 2026-10-23): no LoadURL of 200 ms or more in 55 sends.
    // The v5.2 text below still describes four players and 1.4 s; read those numbers as 11 and 4.2 s.
    // Based on YamachanWebUnit 1.1.0 Runtime/Client.cs (official SHA256
    // 57c6be2a92d2cb442d51acfc361cd49e9ef09a6d003258d2b7bb50b4e4ff7e7c). Every change is marked "DM MODIFIED".
    //
    // Why: the official loop calls LoadURL every 0.2 s (twice per byte) on one transport player. A LoadURL that
    // arrives while that player is still opening the previous rtsp URL blocks the main thread until the open ends
    // (about 2 s on the first byte of a session, about 0.3 s on every later byte).
    //
    // What: four transport players (this object's player A plus DmExtraPlayers B, C, D, which a build step adds as
    // child objects). One LoadURL per byte, on the next player in A -> B -> C -> D order that is out of its cooldown.
    // Cooldowns count from the moment LoadURL RETURNED: 4.2 s after a player's first LoadURL of the session, 1.4 s
    // after later ones. Any two LoadURLs are at least 0.2 s apart. The request completes 0.5 s after the last one.
    // These four values were validated in a real client on 2026-10-06 and are constants on purpose.
    //
    // Request handling (DM-WU4-002): a request from the same receiver while one is in flight REPLACES it (official:
    // the new one was dropped and the old one completed, so the old video started). A request from another receiver
    // is rejected with its own OnRequestError. A request is completed only if the receiver's player still wants the
    // ID that was sent (read-only check of YamaPlayer's current track; skipped for receivers that are not YamaPlayer).
    //
    // Post-resolve guard (v5.1): when a request completes, the receiver starts the main video request. In two real
    // client runs (official Client and v5), transport LoadURLs issued within about 5 s after that moment were not
    // processed by VRChat at all. So the first LoadURL of a new request is held until 5.5 s after the previous
    // OnRequestSuccess. This is an observed guard interval, not a documented VRChat rule. It only acts when a new
    // track is requested right after the previous one was handed over; normal playback never waits.
    //
    // If the transport players are not all usable, the request is sent with the official loop and an error is logged.
    // The URL table, the server endpoints and the Receiver callbacks are unchanged.
    // ==========================================================================================================
    [RequireComponent(typeof(VRCAVProVideoPlayer))]
    [UdonBehaviourSyncMode(BehaviourSyncMode.None)]
    public class Client : UdonSharpBehaviour
    {
        public int SendTimes = 2;
        public int MaxLength = 100;
        public string ApiBase = "api.yamachan.moe";
        public VRCUrl[] Urls;

        // DM MODIFIED: transport players B, C, D (set by the DM build step; never edited at runtime).
        public VRCAVProVideoPlayer[] DmExtraPlayers;
        // DM MODIFIED: revision of this file, checked by the DM build step.
        public int DmRevision = 6; // DM v5.4 (v5.2: 5)
        // DM v5.4: code revision for the DM build step. A const is compiled into the type and never stored
        // in a scene, so a DmRevision value saved with a scene-placed Client cannot hide which Client code is installed.
        public const int DmBuildRevision = 6;
        // DM MODIFIED: 1 = a request of the same receiver replaces the request in flight (DM-WU4-002). Callers that
        // refuse to start a request while the official Client is busy read this together with DmRevision.
        public int DmRequestReplacement = 1;

        // DM MODIFIED: validated scheduler values. Do not change without a new real-client validation.
        const int DmPlayerCount = 11; // DM v5.4 (v5.2: 4)
        const float DmFirstUseCooldown = 4.2f;
        const float DmReuseCooldown = 4.2f; // DM v5.4 (v5.2: 1.4f)
        const float DmMinInterval = 0.2f;
        const float DmFinalWait = 0.5f;
        // DM MODIFIED: observed guard interval after OnRequestSuccess (see the header). Separate from the player cooldowns.
        const float DmPostResolveGuard = 5.5f;
        // DM v5.5: wait after an unread request, and the loading mark of YamaPlayer's handles.
        const float DmUnreadFinalWait = 5f;
        float _dmFinalWait = DmFinalWait;
        // The handles this Client marked. The mark also writes a negative value, unique per mark, into _lastLoaded (nothing
        // in YamaPlayer reads it). Every PlayUrl of YamaPlayer writes Time.time (0 or more) there, so the value still being
        // the mark means no load of YamaPlayer started since, even in the same frame. Only then the mark is undone, and the
        // previous _lastLoaded comes back.
        UdonSharpBehaviour[] _dmMarkedHandles = new UdonSharpBehaviour[0];
        float[] _dmMarkedLoaded = new float[0], _dmMarkedSentinel = new float[0];
        // The number of the next mark, 1 to DmMarkCycle. Every value is exact as a float, and it starts again only after a
        // million marks: every mark is undone or overwritten by YamaPlayer before the next request, so no old one is left.
        public const int DmMarkCycle = 1000000;
        int _dmMarkSerial;

        VRCAVProVideoPlayer _player;

        bool _isLoading = false;
        VRCUrl[] _queue = new VRCUrl[0];
        int _current = 0;
        VRCUrl _requestApi;
        float _lastRequestTime = 0f;
        Receiver _receiver;

        // DM MODIFIED: request identity. _dmGeneration changes whenever the request in flight changes, so delayed
        // events and download callbacks that belong to an earlier request are ignored.
        int _dmGeneration;
        int _dmDownloadGeneration = -1;
        bool _dmDownloadScheduled, _dmDownloading;
        string _dmData = "";
        // DM MODIFIED: highest number of leading bytes that were sent since the server state was last consumed by a
        // completed request. A shorter ID cannot be sent safely while that is larger than its length.
        int _dmServerLength;
        // DM MODIFIED: scheduler state. Use counts and return times are kept for the whole session.
        bool _dmScheduler, _dmStarted;
        float[] _dmLastReturn = new float[DmPlayerCount];
        int[] _dmUseCount = new int[DmPlayerCount];
        int _dmNextSlot;
        float _dmEligibleAt, _dmLastAnyReturn = -100f, _dmFirstAt;
        int _dmSent;
        float _dmWorstCallMs;
        // DM MODIFIED: post-resolve guard. _dmLastSuccessAt = when this Client last called OnRequestSuccess.
        float _dmLastSuccessAt = -100f, _dmGuardUntil, _dmRequestAt, _dmGuardWaitMs;

        public bool IsLoading => _isLoading || _requestApi != null;

        void Start()
        {
            _player = GetComponent<VRCAVProVideoPlayer>();
        }

        void Update() {
            if (!_isLoading) return;

            // DM MODIFIED: the scheduler replaces the fixed 0.2 s loop.
            if (_dmScheduler) { DmSchedulerUpdate(); return; }

            if (Time.realtimeSinceStartup < _dmGuardUntil) return; // DM MODIFIED: post-resolve guard
            if (Time.time - _lastRequestTime < 0.2f) return;

            if (_current == _queue.Length)
            {
                if (_dmFinalWait > DmFinalWait && Time.realtimeSinceStartup - _dmLastAnyReturn < _dmFinalWait) return; // DM v5.5
                DmFinish(); // DM MODIFIED: completion moved into one place
                return;
            }

            _lastRequestTime = Time.time;
            VRCUrl url = _queue[_current];
            _current++;
            if (_current > _dmServerLength) _dmServerLength = _current; // DM MODIFIED

            for (int i = 0; i < SendTimes; i++)
            {
                _player.LoadURL(url);
            }
            _dmLastAnyReturn = Time.realtimeSinceStartup; // DM MODIFIED
        }

        // DM MODIFIED: one LoadURL per byte on the next transport player (A -> B -> C -> D order) that is out of its
        // cooldown. Cooldowns count from the moment LoadURL returned, so a LoadURL that blocked does not shorten them.
        void DmSchedulerUpdate()
        {
            float now = Time.realtimeSinceStartup;
            if (!_dmStarted)
            {
                if (now < _dmGuardUntil) return; // post-resolve guard: nothing is sent yet
                _dmGuardWaitMs = _dmGuardUntil > 0f ? (now - _dmRequestAt) * 1000f : 0f;
                _dmStarted = true; _dmFirstAt = now; _dmSent = 0; _dmWorstCallMs = 0f;
            }
            if (_current == _queue.Length)
            {
                if (now - _dmLastAnyReturn < _dmFinalWait) return; // DM v5.5
                Debug.Log("[DM Modified WebUnit] v5.5 scheduler: " + _dmSent + " LoadURL on " + DmPlayerCount + " transport players in " + Mathf.RoundToInt((now - _dmFirstAt) * 1000f) + " ms, worst call " + Mathf.RoundToInt(_dmWorstCallMs) + " ms, post-resolve guard waited " + Mathf.RoundToInt(_dmGuardWaitMs) + " ms");
                DmFinish();
                return;
            }

            if (now < _dmEligibleAt) return; // global minimum interval (and the wait after a replaced request)

            int slot = -1; float cooldown = 0f;
            for (int k = 0; k < DmPlayerCount; k++)
            {
                int s = (_dmNextSlot + k) % DmPlayerCount;
                float c = _dmUseCount[s] == 0 ? 0f : _dmUseCount[s] == 1 ? DmFirstUseCooldown : DmReuseCooldown;
                if (_dmUseCount[s] == 0 || now - _dmLastReturn[s] >= c) { slot = s; cooldown = c; break; }
            }
            if (slot < 0) return; // every player is cooling down

            VRCUrl url = _queue[_current];
            _current++;
            if (_current > _dmServerLength) _dmServerLength = _current;
            float before = Time.realtimeSinceStartup;
            if (slot == 0) _player.LoadURL(url);
            else DmExtraPlayers[slot - 1].LoadURL(url);
            float after = Time.realtimeSinceStartup;
            float callMs = (after - before) * 1000f;
            if (callMs > _dmWorstCallMs) _dmWorstCallMs = callMs;
            _dmSent++;
            _dmLastReturn[slot] = after; _dmUseCount[slot]++;
            _dmNextSlot = (slot + 1) % DmPlayerCount;
            _dmLastAnyReturn = after; _dmEligibleAt = after + DmMinInterval;
        }

        // DM MODIFIED: every byte was sent. Complete the request only if it is still the one the receiver wants.
        void DmFinish()
        {
            _isLoading = false;
            _current = 0;
            DmMarkLoading(false); // DM v5.5

            if (!DmStillWanted())
            {
                Debug.LogWarning("[DM Modified WebUnit] request for '" + _dmData + "' is no longer the current track; it is dropped and nothing is played for it");
                clear();
                return;
            }

            if (_requestApi.Equals(VRCUrl.Empty))
            {
                // clear() first: the callback may start a new request.
                Receiver receiver = _receiver;
                clear();
                _dmServerLength = 0; // the receiver now asks the server for this ID, which consumes the server state
                _dmLastSuccessAt = Time.realtimeSinceStartup; // origin of the post-resolve guard
                receiver.OnRequestSuccess(null);
                return;
            }

            _dmDownloadScheduled = true;
            _dmDownloadGeneration = _dmGeneration;
            SendCustomEventDelayedSeconds(nameof(StartDownload), 0.3f);
        }

        // DM MODIFIED: read-only check of the receiver's YamaPlayer (VideoResolver._controller, Controller._track =
        // object[] { player type, title, VRCUrl, original url }). False only on positive evidence that the player's
        // current track is a different one; a receiver without these variables is not checked.
        bool DmStillWanted()
        {
            if (!Utilities.IsValid(_receiver)) return false;
            object controllerObject = _receiver.GetProgramVariable("_controller");
            if (controllerObject == null) return true;
            IUdonEventReceiver controller = (IUdonEventReceiver)controllerObject;
            object trackObject = controller.GetProgramVariable("_track");
            if (trackObject == null) return true;
            object[] track = (object[])trackObject;
            if (track.Length < 4) return true;
            string url = (string)track[3];
            if (string.IsNullOrEmpty(url))
            {
                VRCUrl vrcUrl = (VRCUrl)track[2];
                url = vrcUrl == null ? "" : vrcUrl.Get();
            }
            return !string.IsNullOrEmpty(_dmData) && url.Contains(_dmData);
        }

        // DM MODIFIED: all four transport players present, distinct and active.
        bool DmPlayersUsable()
        {
            if (!Utilities.IsValid(_player)) return false;
            if (DmExtraPlayers == null || DmExtraPlayers.Length != DmPlayerCount - 1) return false;
            for (int i = 0; i < DmExtraPlayers.Length; i++)
            {
                VRCAVProVideoPlayer extra = DmExtraPlayers[i];
                if (!Utilities.IsValid(extra)) return false;
                if (extra == _player) return false;
                if (!extra.gameObject.activeInHierarchy) return false;
                for (int k = 0; k < i; k++) if (DmExtraPlayers[k] == extra) return false;
            }
            return true;
        }

        // DM v5.5: while a request is sent, YamaPlayer's handles are stopped and not loading, so VideoPlayerHandle.Stop
        // returns at once and a stop is lost. They are marked as loading (the truth: this request is loading) until the
        // request ends. A stop then runs YamaPlayer's own OnVideoStop, which clears the track, and DmStillWanted drops it.
        // Receivers that are not a YamaPlayer resolver are not touched.
        void DmMarkLoading(bool loading)
        {
            if (!loading)
            {
                for (int i = 0; i < _dmMarkedHandles.Length; i++)
                {
                    UdonSharpBehaviour previous = _dmMarkedHandles[i];
                    if (!Utilities.IsValid(previous)) continue;
                    object previousLoaded = previous.GetProgramVariable("_lastLoaded");
                    if (previousLoaded == null || (float)previousLoaded != _dmMarkedSentinel[i]) continue; // YamaPlayer's own load: not ours
                    previous.SetProgramVariable("_loading", false);
                    previous.SetProgramVariable("_lastLoaded", _dmMarkedLoaded[i]);
                }
                _dmMarkedHandles = new UdonSharpBehaviour[0];
                _dmMarkedLoaded = new float[0];
                _dmMarkedSentinel = new float[0];
                return;
            }
            DmMarkLoading(false); // a replacing request marks again from a clean state
            if (!Utilities.IsValid(_receiver)) return;
            object controllerObject = _receiver.GetProgramVariable("_controller");
            if (controllerObject == null) return;
            object handlesObject = ((IUdonEventReceiver)controllerObject).GetProgramVariable("_videoPlayerHandles");
            if (handlesObject == null) return;
            Component[] handles = (Component[])handlesObject;
            UdonSharpBehaviour[] marked = new UdonSharpBehaviour[handles.Length * 2];
            float[] loadedAt = new float[handles.Length * 2];
            float[] sentinel = new float[handles.Length * 2];
            int count = 0;
            for (int i = 0; i < handles.Length; i++)
            {
                UdonSharpBehaviour handle = (UdonSharpBehaviour)handles[i];
                if (!Utilities.IsValid(handle)) continue;
                object fallback = handle.GetProgramVariable("_fallbackHandle");
                for (int k = 0; k < 2; k++)
                {
                    UdonSharpBehaviour target = k == 0 ? handle : (fallback == null ? null : (UdonSharpBehaviour)fallback);
                    if (!Utilities.IsValid(target)) continue;
                    object targetLoading = target.GetProgramVariable("_loading");
                    object targetLoaded = target.GetProgramVariable("_lastLoaded");
                    if (targetLoading == null || targetLoaded == null || (bool)targetLoading) continue; // already loading: YamaPlayer's, not ours
                    _dmMarkSerial = _dmMarkSerial % DmMarkCycle + 1;
                    sentinel[count] = -(float)_dmMarkSerial;
                    target.SetProgramVariable("_loading", true);
                    target.SetProgramVariable("_lastLoaded", sentinel[count]);
                    marked[count] = target; loadedAt[count] = (float)targetLoaded; count++;
                }
            }
            _dmMarkedHandles = new UdonSharpBehaviour[count];
            _dmMarkedLoaded = new float[count];
            _dmMarkedSentinel = new float[count];
            for (int i = 0; i < count; i++) { _dmMarkedHandles[i] = marked[i]; _dmMarkedLoaded[i] = loadedAt[i]; _dmMarkedSentinel[i] = sentinel[i]; }
        }

        public void StartDownload()
        {
            // DM MODIFIED: ignore the delayed event of a request that was replaced meanwhile.
            if (!_dmDownloadScheduled || _dmDownloadGeneration != _dmGeneration || _requestApi == null) return;
            _dmDownloadScheduled = false;
            _dmDownloading = true;
            VRCStringDownloader.LoadUrl(_requestApi, (IUdonEventReceiver)this);
        }

        public override void OnStringLoadSuccess(IVRCStringDownload result)
        {
            if (!DmDownloadIsCurrent(result)) return; // DM MODIFIED
            _dmDownloading = false;
            Receiver receiver = _receiver;
            clear();
            _dmServerLength = 0;
            _dmLastSuccessAt = Time.realtimeSinceStartup;
            receiver.OnRequestSuccess(result);
        }

        public override void OnStringLoadError(IVRCStringDownload result)
        {
            if (!DmDownloadIsCurrent(result)) return; // DM MODIFIED
            _dmDownloading = false;
            Receiver receiver = _receiver;
            clear();
            receiver.OnRequestError();
        }

        // DM MODIFIED: a download result counts only for the request that started it.
        bool DmDownloadIsCurrent(IVRCStringDownload result)
        {
            if (!_dmDownloading || _dmDownloadGeneration != _dmGeneration) return false;
            if (_requestApi == null || !Utilities.IsValid(_receiver)) return false;
            return result == null || result.Url == null || result.Url.Get() == _requestApi.Get();
        }

        void clear()
        {
            _queue = new VRCUrl[0];
            _requestApi = null;
            _receiver = null;
        }

        public bool Request(VRCUrl req, string data, Receiver target)
        {
            // DM MODIFIED: errors go to the receiver of the request that is refused (official: to the receiver of
            // the request in flight, which is null when the Client is idle).
            if (!Utilities.IsValid(target)) return false;
            if (req == null || data == null) { target.OnRequestError(); return false; }

            byte[] byteData = Encoding.UTF8.GetBytes(data);
            if (byteData.Length > MaxLength )
            {
                target.OnRequestError();
                return false;
            }

            bool replaced = false;
            if (IsLoading)
            {
                if (target != _receiver)
                {
                    Debug.LogWarning("[DM Modified WebUnit] busy with a request of another receiver; the new request for '" + data + "' is refused");
                    target.OnRequestError();
                    return false;
                }
                // DM MODIFIED (DM-WU4-002): the newer request of the same receiver replaces the one in flight.
                replaced = true;
            }

            // DM MODIFIED: from here on the request in flight (if any) is no longer valid.
            _dmGeneration++;
            _dmDownloadScheduled = false;
            _dmDownloading = false;

            if (byteData.Length < _dmServerLength)
            {
                // Bytes of an earlier, unfinished request are still on the server beyond the end of this ID, and they
                // cannot be removed. Sending this ID could resolve to a different video, so nothing is sent.
                Debug.LogError("[DM Modified WebUnit] '" + data + "' (" + byteData.Length + " bytes) cannot be sent safely: " + _dmServerLength + " bytes of an unfinished request are on the server. Play a track with an ID of at least that length first.");
                _isLoading = false;
                _current = 0;
                DmMarkLoading(false); // DM v5.5: before clear(), which forgets the receiver
                clear();
                target.OnRequestError();
                return false;
            }

            _queue = new VRCUrl[byteData.Length];
            for (int i = 0; i < byteData.Length; i++)
            {
                VRCUrl targetUrl = Urls[i * 256 + byteData[i]];
                _queue[i] = targetUrl;
            }

            _requestApi = req;
            _receiver = target;
            _isLoading = true;
            _current = 0;

            // DM MODIFIED: choose the send loop for this request.
            _dmData = data;
            _dmStarted = false;
            // DM MODIFIED: post-resolve guard, counted from the last OnRequestSuccess of this Client.
            _dmRequestAt = Time.realtimeSinceStartup;
            _dmGuardUntil = 0f; _dmGuardWaitMs = 0f;
            if (_dmRequestAt - _dmLastSuccessAt < DmPostResolveGuard)
            {
                _dmGuardUntil = _dmLastSuccessAt + DmPostResolveGuard;
                Debug.Log("[DM Modified WebUnit] post-resolve guard: the previous request completed " + Mathf.RoundToInt((_dmRequestAt - _dmLastSuccessAt) * 1000f) + " ms ago; the first LoadURL for '" + data + "' waits " + Mathf.RoundToInt((_dmGuardUntil - _dmRequestAt) * 1000f) + " ms");
            }
            // DM v5.5: bytes of an unread request are still on the server; this request waits until its own have arrived.
            _dmFinalWait = _dmServerLength > 0 ? DmUnreadFinalWait : DmFinalWait;
            DmMarkLoading(true);
            bool wantScheduler = true;
            _dmScheduler = wantScheduler;
            if (_dmScheduler && !DmPlayersUsable())
            {
                _dmScheduler = false;
                Debug.LogError("[DM Modified WebUnit] the 11 transport players are not all present and active; this request uses the official loop");
            }
            if (replaced)
            {
                // The last LoadURL of the replaced request needs the same time to reach the server as the last
                // byte of a normal request, or it could arrive after a byte of this request.
                float wait = _dmLastAnyReturn + DmFinalWait - Time.realtimeSinceStartup;
                if (wait > 0f)
                {
                    if (_dmEligibleAt < _dmLastAnyReturn + DmFinalWait) _dmEligibleAt = _dmLastAnyReturn + DmFinalWait;
                    _lastRequestTime = Time.time + wait - 0.2f;
                }
                Debug.Log("[DM Modified WebUnit] the request in flight was replaced by '" + data + "'");
            }

            return true;
        }

        public int GetPercentage() {
            if (!_isLoading) return 100;

            return Mathf.RoundToInt((float)_current / (float)_queue.Length * 100);
        }
    }
}
