using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace ServiceSim.EditorTools
{
    /// <summary>
    /// 段階3：18条件 × 種 を、1回の Play の中で順に回す（Run All）。
    /// すでに書き出してある条件は飛ばせるので、途中から再開できる。
    ///
    /// 検査1〜3（速くした回し方でも同じ結果になるかの確かめ）もここから回す。
    /// </summary>
    public static class ServiceSimStage3
    {
        [MenuItem("ServiceSim/Stage 3/Run All（18条件 × 種）", false, 70)]
        public static void RunAll()
        {
            ExperimentRunner runner; ExperimentPlan plan;
            if (!ServiceSimRunSupport.Prepare(out runner, out plan)) return;

            StoreLayout layout = UnityEngine.Object.FindObjectOfType<StoreBuilder>().layout;
            List<ExperimentRunner.Job> jobs = BuildSweep(plan, layout, plan.measureCaptureDeltaTime, "");
            int all = jobs.Count;
            if (plan.stage3Resume) jobs = SkipDone(jobs);

            if (jobs.Count == 0)
            {
                Debug.Log("[ServiceSim] 段階3：すべて書き出し済みです（" + all + " 条件）。" +
                          "やり直すときは ExperimentPlan の stage3Resume を外すか、フォルダを消してください");
                return;
            }

            Launch(runner, plan, jobs, plan.measureCaptureDeltaTime, "stage3",
                   "段階3 Run All：" + jobs.Count + " / " + all + " 条件（残り）");
        }

        [MenuItem("ServiceSim/Stage 3/検査1（刻みだけを見る：空いている・種0）", false, 72)]
        public static void Check1()
        {
            ExperimentRunner runner; ExperimentPlan plan;
            if (!ServiceSimRunSupport.Prepare(out runner, out plan)) return;

            List<ExperimentRunner.Job> jobs = new List<ExperimentRunner.Job>();
            jobs.Add(One(plan, plan.trialAisleWidthIndex, CrowdLevel.Empty, plan.trialRobots, 0,
                         "check1_ref_002"));
            jobs.Add(One(plan, plan.trialAisleWidthIndex, CrowdLevel.Empty, plan.trialRobots, 0,
                         "check1_fast_005"));

            // 1本めは確かめ用の刻み、2本めは計測用の刻み（Run All が条件ごとに刻みを変えられないため2回に分ける）
            Debug.Log("[ServiceSim] 検査1：空いている・種0 を、確かめ用の刻み " +
                      plan.referenceCaptureDeltaTime.ToString("0.###") + " 秒で1回、" +
                      "計測用の刻み " + plan.measureCaptureDeltaTime.ToString("0.###") + " 秒で1回。" +
                      "\n  いまは確かめ用の刻みで1回だけ回します。おわったら同じメニューをもう一度押してください");

            List<ExperimentRunner.Job> first = new List<ExperimentRunner.Job>();
            first.Add(Directory.Exists(jobs[0].folder) ? jobs[1] : jobs[0]);
            float step = Directory.Exists(jobs[0].folder) ? plan.measureCaptureDeltaTime : plan.referenceCaptureDeltaTime;
            Launch(runner, plan, first, step, "check1", "検査1");
        }

        [MenuItem("ServiceSim/Stage 3/検査2（種5つで 0.05 を回す）", false, 73)]
        public static void Check2Fast()
        {
            RunCheck2(false);
        }

        [MenuItem("ServiceSim/Stage 3/検査2（種5つで 0.02 を回す）", false, 74)]
        public static void Check2Ref()
        {
            RunCheck2(true);
        }

        static void RunCheck2(bool reference)
        {
            ExperimentRunner runner; ExperimentPlan plan;
            if (!ServiceSimRunSupport.Prepare(out runner, out plan)) return;

            float step = reference ? plan.referenceCaptureDeltaTime : plan.measureCaptureDeltaTime;
            string tag = reference ? "check2_ref_002" : "check2_fast_005";

            List<ExperimentRunner.Job> jobs = new List<ExperimentRunner.Job>();
            int[] seeds = plan.seeds != null && plan.seeds.Length > 0 ? plan.seeds : new int[] { 0, 1, 2, 3, 4 };
            for (int i = 0; i < seeds.Length; i++)
                jobs.Add(One(plan, plan.trialAisleWidthIndex, plan.trialCrowd, plan.trialRobots, seeds[i], tag));

            if (plan.stage3Resume) jobs = SkipDone(jobs);
            if (jobs.Count == 0) { Debug.Log("[ServiceSim] 検査2：すべて書き出し済みです"); return; }

            Launch(runner, plan, jobs, step, tag,
                   "検査2（1コマ " + step.ToString("0.###") + " 秒）：" + jobs.Count + " 回");
        }

        [MenuItem("ServiceSim/Stage 3/出力フォルダを開く", false, 90)]
        public static void OpenOutput()
        {
            ExperimentPlan plan = AssetDatabase.LoadAssetAtPath<ExperimentPlan>(ServiceSimSetup.ExperimentPlanPath);
            if (plan == null) return;
            if (!Directory.Exists(plan.stage3OutputRoot))
            {
                Debug.LogWarning("[ServiceSim] まだありません: " + plan.stage3OutputRoot);
                return;
            }
            EditorUtility.RevealInFinder(plan.stage3OutputRoot);
        }

        // ---------------- 組み立て ----------------

        static List<ExperimentRunner.Job> BuildSweep(ExperimentPlan plan, StoreLayout layout,
                                                     float step, string tag)
        {
            List<ExperimentRunner.Job> jobs = new List<ExperimentRunner.Job>();
            int[] widths = plan.aisleWidthIndices != null ? plan.aisleWidthIndices : new int[] { 0, 1, 2 };
            CrowdLevel[] crowds = plan.crowdLevels != null ? plan.crowdLevels
                : new CrowdLevel[] { CrowdLevel.Empty, CrowdLevel.Normal, CrowdLevel.Busy };
            int[] robots = plan.robotCounts != null ? plan.robotCounts : new int[] { 1, 2 };
            int[] seeds = plan.seeds != null && plan.seeds.Length > 0 ? plan.seeds : new int[] { 0 };

            for (int w = 0; w < widths.Length; w++)
                for (int c = 0; c < crowds.Length; c++)
                    for (int r = 0; r < robots.Length; r++)
                        for (int s = 0; s < seeds.Length; s++)
                            jobs.Add(One(plan, widths[w], crowds[c], robots[r], seeds[s], tag));
            return jobs;
        }

        static ExperimentRunner.Job One(ExperimentPlan plan, int widthIndex, CrowdLevel crowd,
                                        int robots, int seed, string tag)
        {
            ExperimentRunner.Job j = new ExperimentRunner.Job();
            j.aisleWidthIndex = widthIndex;
            j.crowd = crowd;
            j.robots = robots;
            j.seed = seed;

            string root = tag.Length > 0 && tag.StartsWith("check")
                ? Path.Combine(plan.stage3OutputRoot, tag)
                : Path.Combine(plan.stage3OutputRoot, DateTime.Now.ToString("yyyyMMdd") + "_" + plan.runName);

            j.folder = Path.Combine(root,
                "w" + widthIndex + "_" + ExperimentPlan.CrowdName(crowd) + "_r" + robots + "_s" + seed);
            return j;
        }

        /// <summary>すでに summary.json がある条件は飛ばす（途中から再開）</summary>
        static List<ExperimentRunner.Job> SkipDone(List<ExperimentRunner.Job> jobs)
        {
            List<ExperimentRunner.Job> left = new List<ExperimentRunner.Job>();
            int skipped = 0;
            for (int i = 0; i < jobs.Count; i++)
            {
                if (File.Exists(Path.Combine(jobs[i].folder, "summary.json"))) { skipped++; continue; }
                left.Add(jobs[i]);
            }
            if (skipped > 0) Debug.Log("[ServiceSim] 書き出し済みを飛ばしました: " + skipped + " 条件");
            return left;
        }

        static void Launch(ExperimentRunner runner, ExperimentPlan plan,
                           List<ExperimentRunner.Job> jobs, float step, string label, string what)
        {
            runner.SetQueue(jobs);
            runner.timeMode = ExperimentRunner.TimeMode.FixedStep;
            runner.captureDeltaTimeOverride = step;
            runner.runLabel = label;
            runner.viewMode = false;      // 段階3・検査は見る用ではない
            runner.runOnPlay = true;
            EditorUtility.SetDirty(runner);

            Debug.Log("[ServiceSim] " + what + "（Play に入ります）" +
                      "\n  1コマ " + step.ToString("0.###") + " 秒 / 1回あたり店の中 " +
                      (plan.warmupMinutes + plan.measureMinutes) + " 分" +
                      "\n  描画を止める: " + (plan.disableRenderingWhileRunning ? "はい" : "いいえ") +
                      "\n  置き場所: " + (jobs.Count > 0 ? Path.GetDirectoryName(jobs[0].folder) : "-") +
                      "\n  おわると自動で Play を抜けます。Console の「とちゅう」で進みが見られます");

            EditorApplication.EnterPlaymode();
        }
    }
}
