using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

namespace ServiceSim
{
    /// <summary>
    /// 人どうしのすれ違い。細い通路で押し合って動けなくなったときに解く。
    ///   1. 前に進めない状態が 1 秒続いたら、その人の半径を細める（体を横に向ける）
    ///   2. それでも 3 秒抜けられなければ、片方が下がる（仕事中のスタッフより客が下がる）
    ///   3. 1回の詰まりを people_jams.csv に1行で残す
    ///
    /// この script は人だけを扱う。数字は PeopleSpec の .asset に置く。
    /// </summary>
    public class JamWatcher : MonoBehaviour
    {
        /// <summary>詰まり1回ぶんの記録</summary>
        public struct JamRow
        {
            public float tS;        // 店の中の時刻
            public float x, z;
            public string aisle;
            public int people;      // 詰まっていた人数
            public float durationS;
            public string resolved; // どう解けたか

            /// <summary>
            /// 近くでロボットが止まっていたか（B9）。
            /// 停止点を通路の中央にすると、通路 1.0 m では停まった台の左右が 0.25 m ずつになり、
            /// 人（半径 0.2 m）はどちら側も通れない。その回数を数える。
            /// </summary>
            public bool robotBlocked;

            /// <summary>その台の番号（robotBlocked のときだけ）</summary>
            public int robotId;
        }

        [Header("設定")]
        public PeopleSpec spec;
        public ServiceOps ops;
        public StoreBuilder store;

        [Tooltip("この距離の中にいる動けない人を、同じ詰まりとして数える（m）")]
        public float clusterRadius = 1.0f;

        [Tooltip("この距離の中に止まっているロボットがいたら、そのロボットが原因とみなす（m）")]
        public float robotNearM = 1.5f;

        [Header("いまの様子（読むだけ）")]
        [SerializeField] int _narrowed;
        [SerializeField] int _jams;
        [SerializeField] int _robotBlockedJams;

        class State
        {
            public float stuckS;
            public bool narrowed;
            public bool backedOff;
            public float startS;
            public Vector3 startPos;
            public int people;
            public bool robotBlocked;   // 詰まっている間に、近くで止まっているロボットがいた
            public int robotId;
        }

        readonly Dictionary<PersonBody, State> _state = new Dictionary<PersonBody, State>();
        readonly List<JamRow> _rows = new List<JamRow>();

        public IReadOnlyList<JamRow> Rows { get { return _rows; } }
        public int JamCount { get { return _jams; } }

        /// <summary>人どうしの詰まりのうち、近くでロボットが止まっていたもの（B9）</summary>
        public int RobotBlockedJamCount { get { return _robotBlockedJams; } }

        public float TotalJamSeconds
        {
            get
            {
                float s = 0f;
                for (int i = 0; i < _rows.Count; i++) s += _rows[i].durationS;
                return s;
            }
        }

        public void Setup()
        {
            _state.Clear();
            _rows.Clear();
            _jams = 0;
            _narrowed = 0;
            _robotBlockedJams = 0;
        }

        public void Tick(float dt)
        {
            if (spec == null || ops == null) return;

            int narrowed = 0;
            IReadOnlyList<PersonBody> all = PersonBody.All;

            for (int i = 0; i < all.Count; i++)
            {
                PersonBody p = all[i];
                if (p == null || !p.walksInAisle) continue;

                NavMeshAgent a = p.GetComponent<NavMeshAgent>();
                if (a == null || !a.isActiveAndEnabled || !a.isOnNavMesh) { Clear(p); continue; }

                bool wantsToMove = a.hasPath && a.remainingDistance > a.stoppingDistance + 0.05f;
                bool stuck = wantsToMove && p.Speed < spec.jamStuckSpeed;

                if (!stuck) { Resolve(p, a, "そのまま抜けた"); continue; }

                State st;
                if (!_state.TryGetValue(p, out st))
                {
                    st = new State();
                    st.startS = ops.NowS;
                    st.startPos = p.transform.position;
                    _state[p] = st;
                }
                st.stuckS += dt;
                st.people = Mathf.Max(st.people, CountStuckNear(p));

                // 近くで止まっているロボットがいたら覚えておく（B9）
                if (!st.robotBlocked)
                {
                    int id = StoppedRobotNear(p.transform.position);
                    if (id > 0) { st.robotBlocked = true; st.robotId = id; }
                }

                // 1. 体を横に向ける
                if (!st.narrowed && st.stuckS >= spec.jamNarrowAfterSec)
                {
                    st.narrowed = true;
                    a.radius = spec.jamNarrowRadius;
                }
                if (st.narrowed) narrowed++;

                // 2. それでも抜けられなければ、片方が下がる
                if (!st.backedOff && st.stuckS >= spec.jamBackOffAfterSec && ShouldBackOff(p))
                {
                    st.backedOff = true;
                    Vector3 to = NearestWideAislePoint(p.transform.position);
                    PeopleNav.Go(a, to);
                }
            }

            _narrowed = narrowed;
        }

        /// <summary>仕事中のスタッフより、客のほうが下がる</summary>
        bool ShouldBackOff(PersonBody p)
        {
            if (p.kind != PersonKind.Staff) return true;
            StaffAgent s = p.GetComponent<StaffAgent>();
            return s == null || s.CurrentJob == null;   // 手が空いているスタッフなら下がる
        }

        /// <summary>
        /// その点の近くで止まっているロボットの番号。いなければ 0。
        /// 「卓の前で止まっていて人が通れなかった」を数えるために使う（B9）。
        /// </summary>
        int StoppedRobotNear(Vector3 at)
        {
            if (ops == null) return 0;
            IList<ServingRobotController> robots = ops.Robots;
            for (int i = 0; i < robots.Count; i++)
            {
                ServingRobotController r = robots[i];
                if (r == null) continue;
                if (r.CurrentPhase == ServingRobotController.Phase.Idle ||
                    r.CurrentPhase == ServingRobotController.Phase.Done) continue;
                if (r.LastStepM > 0.002f) continue;   // 動いている台は数えない

                Vector3 d = r.transform.position - at;
                d.y = 0f;
                if (d.magnitude <= robotNearM) return r.robotId;
            }
            return 0;
        }

        int CountStuckNear(PersonBody p)
        {
            int n = 1;
            IReadOnlyList<PersonBody> all = PersonBody.All;
            for (int i = 0; i < all.Count; i++)
            {
                PersonBody o = all[i];
                if (o == null || o == p || !o.walksInAisle) continue;
                if (o.Speed >= spec.jamStuckSpeed) continue;
                Vector3 d = o.transform.position - p.transform.position;
                d.y = 0f;
                if (d.magnitude <= clusterRadius) n++;
            }
            return n;
        }

        void Resolve(PersonBody p, NavMeshAgent a, string how)
        {
            State st;
            if (!_state.TryGetValue(p, out st)) return;
            _state.Remove(p);

            if (st.narrowed && a != null) a.radius = spec.personRadius;

            // 細める前に抜けた短いものは、詰まりとして数えない
            if (st.stuckS < spec.jamNarrowAfterSec) return;

            JamRow r = new JamRow();
            r.tS = st.startS;
            r.x = st.startPos.x;
            r.z = st.startPos.z;
            r.aisle = AisleNameAt(st.startPos);
            r.people = Mathf.Max(2, st.people);
            r.durationS = st.stuckS;
            r.resolved = st.backedOff ? "下がって抜けた" : (st.narrowed ? "体を横に向けて抜けた" : how);
            r.robotBlocked = st.robotBlocked;
            r.robotId = st.robotId;
            _rows.Add(r);
            _jams++;
            if (st.robotBlocked) _robotBlockedJams++;
        }

        void Clear(PersonBody p)
        {
            State st;
            if (!_state.TryGetValue(p, out st)) return;
            _state.Remove(p);
        }

        string AisleNameAt(Vector3 p)
        {
            if (store == null) return "";
            string wide = "";
            IList<StoreBuilder.AisleInfo> aisles = store.Aisles;
            for (int i = 0; i < aisles.Count; i++)
            {
                Bounds b = aisles[i].zone;
                if (p.x < b.min.x || p.x > b.max.x || p.z < b.min.z || p.z > b.max.z) continue;
                if (aisles[i].narrow) return aisles[i].name;
                if (wide.Length == 0) wide = aisles[i].name;
            }
            return wide;
        }

        /// <summary>いちばん近い太い通路（太い通路・横通路）の点</summary>
        Vector3 NearestWideAislePoint(Vector3 from)
        {
            if (store == null) return from;
            float best = float.MaxValue;
            Vector3 pick = from;
            IList<StoreBuilder.AisleInfo> aisles = store.Aisles;
            for (int i = 0; i < aisles.Count; i++)
            {
                if (aisles[i].narrow) continue;
                Vector3 c = aisles[i].zone.ClosestPoint(new Vector3(from.x, 0f, from.z));
                c.y = 0f;
                float d = Vector3.Distance(new Vector3(from.x, 0f, from.z), c);
                if (d < best) { best = d; pick = c; }
            }
            return pick;
        }
    }
}
