using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Profiling;
#if VIKPI_INPUT_SYSTEM && ENABLE_INPUT_SYSTEM
using UnityEngine.InputSystem;
using InputTouchPhase = UnityEngine.InputSystem.TouchPhase;
#endif

namespace ViKPI.Internal
{
    /// <summary>
    /// Reads touches (or the mouse, on desktop and in the editor) every frame and emits down/move/up
    /// samples in normalized screen coordinates with a top-left origin, matching the video frames.
    /// Moves are thinned to what a heatmap and replay overlay need.
    /// </summary>
    internal sealed class TouchTracker
    {
        private const float MoveIntervalSec = 0.05f;
        private const float MoveMinDistance = 0.004f;
        private const int MouseFinger = 0;

        private struct Last
        {
            public float X, Y, Time;
        }

        private readonly Dictionary<int, Last> _last = new Dictionary<int, Last>();
        private bool _mouseDown;

        public void Update(long t, string scene, EventBuffer into)
        {
            var w = Screen.width;
            var h = Screen.height;
            if (w <= 0 || h <= 0) return;

#if VIKPI_INPUT_SYSTEM && ENABLE_INPUT_SYSTEM
            var ts = Touchscreen.current;
            var anyTouch = false;
            if (ts != null)
            {
                foreach (var touch in ts.touches)
                {
                    var phase = touch.phase.ReadValue();
                    if (phase == InputTouchPhase.None) continue;
                    anyTouch = true;
                    var id = touch.touchId.ReadValue() & 31;
                    var pos = touch.position.ReadValue();
                    switch (phase)
                    {
                        // Phase stays Began until the next event for that finger; emit the down once.
                        case InputTouchPhase.Began: if (!_last.ContainsKey(id)) Emit(0, id, pos, w, h, t, scene, into); break;
                        case InputTouchPhase.Moved: Emit(1, id, pos, w, h, t, scene, into); break;
                        case InputTouchPhase.Ended:
                        case InputTouchPhase.Canceled:
                            if (_last.ContainsKey(id)) Emit(2, id, pos, w, h, t, scene, into);
                            break;
                    }
                }
            }
            var mouse = Mouse.current;
            if (!anyTouch && mouse != null)
            {
                var pos = mouse.position.ReadValue();
                if (mouse.leftButton.wasPressedThisFrame) { Emit(0, MouseFinger, pos, w, h, t, scene, into); _mouseDown = true; }
                else if (_mouseDown && mouse.leftButton.wasReleasedThisFrame) { Emit(2, MouseFinger, pos, w, h, t, scene, into); _mouseDown = false; }
                else if (_mouseDown && mouse.leftButton.isPressed) Emit(1, MouseFinger, pos, w, h, t, scene, into);
            }
#elif ENABLE_LEGACY_INPUT_MANAGER
            var count = Input.touchCount;
            for (var i = 0; i < count; i++)
            {
                var touch = Input.GetTouch(i);
                var id = touch.fingerId & 31;
                switch (touch.phase)
                {
                    case UnityEngine.TouchPhase.Began: Emit(0, id, touch.position, w, h, t, scene, into); break;
                    case UnityEngine.TouchPhase.Moved: Emit(1, id, touch.position, w, h, t, scene, into); break;
                    case UnityEngine.TouchPhase.Ended:
                    case UnityEngine.TouchPhase.Canceled:
                        if (_last.ContainsKey(id)) Emit(2, id, touch.position, w, h, t, scene, into);
                        break;
                }
            }
            // Touch devices also synthesize mouse events from touches; only read the mouse without touches.
            if (count == 0 && Input.mousePresent)
            {
                Vector2 pos = Input.mousePosition;
                if (Input.GetMouseButtonDown(0)) { Emit(0, MouseFinger, pos, w, h, t, scene, into); _mouseDown = true; }
                else if (_mouseDown && Input.GetMouseButtonUp(0)) { Emit(2, MouseFinger, pos, w, h, t, scene, into); _mouseDown = false; }
                else if (_mouseDown && Input.GetMouseButton(0)) Emit(1, MouseFinger, pos, w, h, t, scene, into);
            }
#endif
        }

        private void Emit(byte phase, int finger, Vector2 screen, int w, int h, long t, string scene, EventBuffer into)
        {
            var x = Mathf.Clamp01(screen.x / w);
            var y = Mathf.Clamp01(1f - screen.y / h);
            var now = Time.unscaledTime;

            if (phase == 1)
            {
                if (!_last.TryGetValue(finger, out var last)) return; // Move without a down we saw.
                if (now - last.Time < MoveIntervalSec) return;
                if (Mathf.Abs(x - last.X) < MoveMinDistance && Mathf.Abs(y - last.Y) < MoveMinDistance) return;
            }

            into.Add(new TouchItem { T = t, Phase = phase, X = x, Y = y, Finger = finger, Scene = scene });
            if (phase == 2) _last.Remove(finger);
            else _last[finger] = new Last { X = x, Y = y, Time = now };
        }
    }

    /// <summary>Once a second: frames per second, 95th percentile frame time, memory and battery.</summary>
    internal sealed class PerfSampler
    {
        private const float WindowSec = 1f;
        private readonly float[] _frameMs = new float[1024];
        private int _count;
        private float _elapsed;

        public void Update(long t, string scene, EventBuffer into)
        {
            var dt = Time.unscaledDeltaTime;
            if (dt <= 0f) return;
            if (_count < _frameMs.Length) _frameMs[_count] = dt * 1000f;
            _count++;
            _elapsed += dt;
            if (_elapsed < WindowSec) return;

            var n = Math.Min(_count, _frameMs.Length);
            Array.Sort(_frameMs, 0, n);
            var p95 = _frameMs[Math.Min(n - 1, (int)Math.Ceiling(n * 0.95) - 1)];
            into.Add(new PerfItem
            {
                T = t,
                Fps = _count / _elapsed,
                FrameMsP95 = p95,
                MemMb = Profiler.GetTotalAllocatedMemoryLong() / (1024f * 1024f),
                Battery = SystemInfo.batteryLevel,
                Scene = scene,
            });
            _count = 0;
            _elapsed = 0;
        }

        /// <summary>Drop the partial window, e.g. after the app was in the background.</summary>
        public void Reset()
        {
            _count = 0;
            _elapsed = 0;
        }
    }

    /// <summary>
    /// Captures exceptions, errors and failed asserts from Unity's log, from any thread. Repeats of
    /// the same message are thinned so an error inside Update can't flood the batch.
    /// </summary>
    internal sealed class ErrorCapture : IDisposable
    {
        private const int MaxPerSession = 250;
        private const long RepeatWindowMs = 1000;

        private readonly Func<long> _now;
        private readonly Func<string> _scene;
        private readonly Func<EventBuffer> _buffer;
        private readonly Dictionary<int, long> _lastSeen = new Dictionary<int, long>();
        private int _sent;

        public ErrorCapture(Func<long> now, Func<string> scene, Func<EventBuffer> buffer)
        {
            _now = now;
            _scene = scene;
            _buffer = buffer;
            Application.logMessageReceivedThreaded += OnLog;
        }

        public void ResetSession()
        {
            lock (_lastSeen)
            {
                _lastSeen.Clear();
                _sent = 0;
            }
        }

        private void OnLog(string message, string stack, LogType type)
        {
            string kind;
            switch (type)
            {
                case LogType.Exception: kind = "exception"; break;
                case LogType.Error: kind = "error"; break;
                case LogType.Assert: kind = "assert"; break;
                default: return;
            }
            if (message != null && message.StartsWith(Log.Prefix, StringComparison.Ordinal)) return; // Our own.

            var buffer = _buffer();
            if (buffer == null) return;
            var t = _now();
            var key = (message ?? "").GetHashCode() ^ type.GetHashCode();
            lock (_lastSeen)
            {
                if (_sent >= MaxPerSession) return;
                if (_lastSeen.TryGetValue(key, out var last) && t - last < RepeatWindowMs) return;
                _lastSeen[key] = t;
                _sent++;
            }

            buffer.Add(new ErrorItem
            {
                T = t,
                Type = kind,
                Message = DeviceInfo.Clip(message, 2000),
                Stack = DeviceInfo.Clip(stack, 16000),
                Scene = _scene() ?? "",
            });
        }

        public void Dispose() => Application.logMessageReceivedThreaded -= OnLog;
    }
}
