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

namespace ServiceSim
{
    /// <summary>
    /// ずっといる人を置く：スタッフと、卓ごとの「座っている客」（椅子を引く仕掛け）。
    /// 歩く客と待合の客は、1組ごとの流れに合わせて GroupManager が出し入れする。
    ///
    /// 置き場所は StoreBuilder から読むだけで、店は作らない。
    /// </summary>
    public class PeopleSpawner : MonoBehaviour
    {
        [Header("設定")]
        public PeopleSpec spec;
        public ServiceSpec service;

        [Tooltip("置き場所を読む先。店は作らない")]
        public StoreBuilder store;

        [Tooltip("卓の空き具合を読む先（空いている卓では椅子を引かない）")]
        public ServiceOps ops;

        [Header("部品")]
        public GameObject staffPrefab;
        public GameObject seatedGuestPrefab;

        PeopleTargets _targets;

        /// <summary>卓の番号（store.Tables と同じ並び）ごとの椅子の出し入れ</summary>
        readonly List<SeatedGuest> _seated = new List<SeatedGuest>();

        public int StaffSpawned { get; private set; }
        public int SeatedSpawned { get; private set; }
        public PeopleTargets Targets { get { return _targets; } }

        /// <summary>その卓の椅子の出し入れ（GroupManager が人の動きに合わせて呼ぶ）</summary>
        public SeatedGuest SeatedAt(int tableIndex)
        {
            if (tableIndex < 0 || tableIndex >= _seated.Count) return null;
            return _seated[tableIndex];
        }

        /// <summary>椅子を引いた回数の合計（run_info.json に出す）</summary>
        public int ChairPullTotal
        {
            get
            {
                int n = 0;
                for (int i = 0; i < _seated.Count; i++) if (_seated[i] != null) n += _seated[i].Pulls;
                return n;
            }
        }

        /// <summary>スタッフと、卓ごとの座っている客を置く</summary>
        public void Spawn(int seed)
        {
            if (spec == null || store == null)
            {
                Debug.LogError("[ServiceSim] PeopleSpawner に PeopleSpec か StoreBuilder が入っていません");
                return;
            }

            Clear();
            _targets = CollectTargets();

            System.Random rng = new System.Random(seed);

            for (int i = 0; i < spec.staffCount; i++)
            {
                GameObject go = Spawn(staffPrefab, "Staff" + (i + 1).ToString("00"),
                                      Scatter(_targets.pantry, 0.8f, rng), true);
                StaffAgent a = go.GetComponent<StaffAgent>();
                if (a != null) a.Configure(spec, service, ops, _targets, seed * 1000 + i, i);
                AttachRobotYield(go, seed * 1000 + 100 + i);
                StaffSpawned++;
            }

            IList<StoreBuilder.TableInfo> tables = store.Tables;
            for (int i = 0; i < tables.Count; i++)
            {
                StoreBuilder.TableInfo t = tables[i];
                GameObject go = Spawn(seatedGuestPrefab, "SeatedGuest_T" + t.tableId.ToString("00"), t.center, false);
                SeatedGuest s = go.GetComponent<SeatedGuest>();
                if (s != null) s.Configure(spec, t.aisleChairs, seed * 1000 + 2000 + t.tableId, ops, i);
                _seated.Add(s);
                PersonBody body = go.GetComponent<PersonBody>();
                if (body != null)
                {
                    body.radius = spec.personRadius;
                    body.walksInAisle = false;
                    body.kind = PersonKind.Seated;
                }
                SeatedSpawned++;
            }
        }

        /// <summary>
        /// 人がロボットをよける仕掛けを付ける（prefab に無くても付く）。
        /// 歩く客の体は GroupManager が出し入れするので、そちらでも同じことをする。
        /// </summary>
        public void AttachRobotYield(GameObject go, int seed)
        {
            if (go == null) return;
            PersonRobotYield y = go.GetComponent<PersonRobotYield>();
            if (y == null) y = go.AddComponent<PersonRobotYield>();
            y.Configure(spec, store, ops, seed);
        }

        public void Clear()
        {
            StaffSpawned = 0;
            SeatedSpawned = 0;
            _targets = null;
            _seated.Clear();
            for (int i = transform.childCount - 1; i >= 0; i--)
            {
                GameObject go = transform.GetChild(i).gameObject;
                if (Application.isPlaying) Destroy(go);
                else DestroyImmediate(go);
            }
        }

        /// <summary>店から行き先を読む</summary>
        public PeopleTargets CollectTargets()
        {
            PeopleTargets t = new PeopleTargets();
            t.foodPass = store.PassPoint;
            t.dishReturn = store.ReturnPoint;
            t.pantry = store.PantryPoint;
            t.register = store.RegisterPoint;
            t.registerBack = store.RegisterBackPoint;
            t.toilet = store.ToiletPoint;
            t.drinkBar = store.DrinkBarPoint;
            t.entrance = store.EntrancePoint;
            t.waiting = store.WaitingPoint;
            t.waitingArea = store.WaitingArea;
            t.staffStandby.AddRange(store.StaffStandbyPoints);

            IList<StoreBuilder.TableInfo> tables = store.Tables;
            for (int i = 0; i < tables.Count; i++) t.tablePoints.Add(tables[i].deliveryPoint);

            // 店に無い場所は、受け渡し口で代わりにする（格子型の店など）
            if (!store.HasPoint(PlaceKind.DishReturn)) t.dishReturn = t.foodPass;
            if (!store.HasPoint(PlaceKind.Pantry)) t.pantry = t.foodPass;
            if (!store.HasPoint(PlaceKind.Entrance)) t.entrance = t.foodPass;
            if (!store.HasPoint(PlaceKind.RegisterBack)) t.registerBack = t.register;
            if (!store.HasPoint(PlaceKind.Waiting)) t.waiting = t.register;
            if (!store.HasPoint(PlaceKind.Toilet)) t.toilet = t.register;
            if (!store.HasPoint(PlaceKind.DrinkBar)) t.drinkBar = t.register;
            return t;
        }

        GameObject Spawn(GameObject prefab, string name, Vector3 position, bool snapToNavMesh)
        {
            GameObject go;
            if (prefab != null) go = Instantiate(prefab, transform);
            else
            {
                go = new GameObject(name);
                go.transform.SetParent(transform, false);
            }
            go.name = name;

            Vector3 p = position;
            if (snapToNavMesh)
            {
                NavMeshHit hit;
                if (NavMesh.SamplePosition(p, out hit, 2.0f, PeopleNav.Filter)) p = hit.position;
            }
            go.transform.position = p;

            if (spec != null)
            {
                PersonBody body = go.GetComponent<PersonBody>();
                if (body != null) body.radius = spec.personRadius;
            }
            return go;
        }

        Vector3 Scatter(Vector3 center, float range, System.Random rng)
        {
            float a = (float)(rng.NextDouble() * System.Math.PI * 2.0);
            float r = (float)rng.NextDouble() * range;
            return center + new Vector3(Mathf.Cos(a) * r, 0f, Mathf.Sin(a) * r);
        }
    }
}
