// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
using Debug = UnityEngine.Debug;

namespace WPFMA.Team
{
    internal enum ReunionAction
    {
        TakeTheirs,
        DeleteHere,
        SendToThem,
        DeleteThere,
        Merge,
        Conflict
    }

    internal enum ReunionChoice
    {
        Mine,
        Theirs,
        Both
    }

    /// <summary>One file that changed while two teammates were apart, and what happens to it.</summary>
    internal sealed class ReunionItem
    {
        public string Path;
        public ReunionAction Action;
        public string Note;
        /// <summary>A Unity file both changed that merged with clashes left: Mine/Theirs picks who wins those.</summary>
        public bool Clashes;
        public ReunionChoice Choice = ReunionChoice.Mine;
        public string MergedTemp;
    }

    /// <summary>
    /// Working apart and meeting again. Both sides remember the last version they shared of every file (the
    /// "agreed" list) and keep a copy of the shared version of Unity's text files (scenes, prefabs, materials,
    /// animators) in Library/WPFMATeam/base. When the same teammate joins again, the host compares the shared
    /// version, its own files and theirs: a change on one side goes to the other, Unity files both changed are
    /// merged object by object with Unity's own merge tool, and the rest waits in the "While you were apart"
    /// window. Nothing changes until the host clicks Sync.
    /// </summary>
    internal static partial class TeamFiles
    {
        private static readonly string[] MergeableExtensions =
        {
            ".unity", ".prefab", ".mat", ".asset", ".controller", ".overridecontroller", ".anim", ".mask",
            ".physicmaterial", ".physicsmaterial2d", ".playable", ".signal", ".lighting", ".rendertexture",
            ".flare", ".guiskin", ".fontsettings", ".cubemap", ".spriteatlas", ".preset", ".terrainlayer", ".mixer"
        };

        private static string BaseFolder
        {
            get { return Path.Combine("Library", "WPFMATeam", "base"); }
        }

        /// <summary>The host's plan while it waits for Sync (null when there's nothing to review).</summary>
        internal static List<ReunionItem> Reunion { get; private set; }

        internal static string ReunionWith { get; private set; }

        private static PeerFiles reunionPeer;
        private static Dictionary<string, string> reunionBase;
        private static Dictionary<string, string> reunionTheirs;
        private static readonly Dictionary<string, KeyValuePair<byte[], string>> reunionFetched = new Dictionary<string, KeyValuePair<byte[], string>>();
        private static readonly HashSet<string> reunionFetching = new HashSet<string>();
        private static readonly HashSet<string> reunionAccept = new HashSet<string>();
        private static readonly HashSet<string> reunionPulls = new HashSet<string>();
        private static bool reunionGuestDone;
        private static bool guestReunion;
        private static double lastBaseCapture = -1000;

        // ---- Shared versions, kept for merging ----------------------------------------------------------------

        /// <summary>A Unity text file (scene, prefab, material...) that Unity's merge tool can merge.</summary>
        internal static bool Mergeable(string path)
        {
            if (!MergeableExtensions.Contains(Path.GetExtension(path).ToLowerInvariant()) || !File.Exists(path))
                return false;
            try
            {
                using (var stream = File.OpenRead(path))
                {
                    var head = new byte[5];
                    return stream.Read(head, 0, 5) == 5 && Encoding.ASCII.GetString(head) == "%YAML";
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        private static string BaseFile(string hash)
        {
            return string.IsNullOrEmpty(hash) ? null : Path.Combine(BaseFolder, hash.Replace(':', '_') + ".yaml");
        }

        /// <summary>
        /// Copies the shared version of each Unity text file while this editor still has it, so a later merge has
        /// the version both started from. Cheap: only files whose copy is missing are read.
        /// </summary>
        private static void CaptureBases(PeerFiles pf, bool force)
        {
            if (pf == null || (!force && TeamSession.Now - lastBaseCapture < 60))
                return;
            lastBaseCapture = TeamSession.Now;
            try
            {
                Directory.CreateDirectory(BaseFolder);
                foreach (var pair in pf.Agreed.ToList())
                {
                    if (!MergeableExtensions.Contains(Path.GetExtension(pair.Key).ToLowerInvariant()))
                        continue;
                    string target = BaseFile(pair.Value);
                    if (target == null || File.Exists(target) || !File.Exists(pair.Key) || CachedHash(pair.Key) != pair.Value)
                        continue;
                    File.Copy(pair.Key, target, true);
                }
                PruneBases();
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA Team] Could not keep the shared versions for merging: " + e.Message);
            }
        }

        /// <summary>
        /// A session (or one teammate) is ending. Scenes edited together live were kept the same by sending each edit,
        /// not the file, so the record of "what we both had" still points at the scene from when it was first shared.
        /// Each side saves its shared scenes now (they match), and that becomes the version a later merge starts from.
        /// </summary>
        private static void RecordLiveScenes(List<PeerFiles> targets)
        {
            if (targets.Count == 0 || EditorApplication.isPlayingOrWillChangePlaymode)
                return;
            foreach (var path in TeamScene.LiveScenes.ToList())
            {
                if (TeamScene.DriftScene == path || !Shared(path))
                    continue;
                var scene = SceneManager.GetSceneByPath(path);
                if (!scene.IsValid() || !scene.isLoaded)
                    continue;
                try
                {
                    if (scene.isDirty)
                        EditorSceneManager.SaveScene(scene);
                }
                catch (Exception e)
                {
                    Debug.LogWarning("[WPFMA Team] Couldn't save " + path + " at the end of the session: " + e.Message);
                    continue;
                }
                string hash = CachedHash(path);
                if (string.IsNullOrEmpty(hash))
                    continue;
                foreach (var pf in targets)
                    if (!pf.Reuniting)
                        pf.Agreed[path] = hash;
            }
            foreach (var pf in targets)
            {
                CaptureBases(pf, true);
                SaveAgreed(pf);
            }
        }

        /// <summary>
        /// Guests never swap files with each other directly - everything goes through the host - so on their own
        /// they'd have no record of each other, and two guests meeting later without the host would start over. While
        /// everyone matches, what a guest has in common with the host is also what it has in common with every other
        /// guest who matches the host, so that record is kept for each of them too. Guests who still had things on
        /// their way are left out: starting over is better than merging from a wrong record.
        /// </summary>
        private static void RecordOtherGuests(List<TeamPeer> others)
        {
            if (TeamSession.IsHost || !knownReady)
                return;
            var host = TeamSession.HostPeer;
            PeerFiles withHost;
            if (host == null || !peers.TryGetValue(host.Id, out withHost) || withHost.Reuniting || withHost.Agreed.Count == 0)
                return;
            if (TeamSession.LocalPending().Count > 0)
                return;
            var lines = withHost.Agreed.Select(pair => pair.Key + "	" + pair.Value).ToArray();
            foreach (var other in others)
            {
                if (other == null || other.IsHost || other.Id == TeamSession.LocalId || !string.IsNullOrEmpty(other.Pending))
                    continue;
                try
                {
                    Directory.CreateDirectory(Path.Combine("Library", "WPFMATeam"));
                    File.WriteAllLines(Path.Combine("Library", "WPFMATeam", "agreed-" + WPFMAPaths.SafeFileName(other.Id) + ".txt"), lines);
                }
                catch (Exception)
                {
                }
            }
        }

        /// <summary>Removes shared copies no teammate's list points at any more.</summary>
        private static void PruneBases()
        {
            if (!Directory.Exists(BaseFolder))
                return;
            var wanted = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            foreach (var pf in peers.Values)
                foreach (var hash in pf.Agreed.Values)
                    wanted.Add(Path.GetFileName(BaseFile(hash) ?? string.Empty));
            foreach (var file in Directory.GetFiles(Path.Combine("Library", "WPFMATeam"), "agreed-*.txt"))
                foreach (var line in File.ReadAllLines(file))
                {
                    int tab = line.IndexOf('\t');
                    if (tab > 0)
                        wanted.Add(Path.GetFileName(BaseFile(line.Substring(tab + 1))));
                }
            foreach (var file in Directory.GetFiles(BaseFolder))
                if (!wanted.Contains(Path.GetFileName(file)))
                    DeleteQuietly(file);
        }

        // ---- Starting --------------------------------------------------------------------------------------------

        /// <summary>Host: a teammate we've worked with before connected. Wait for their file list before syncing anything.</summary>
        private static void HostAwaitReunion(PeerFiles pf)
        {
            pf.Reuniting = true;
            pf.ReunionBase = new Dictionary<string, string>(pf.Agreed);
        }

        /// <summary>Guest: we've worked with this host before. Send what we have now and let the host compare.</summary>
        private static void GuestStartReunion(PeerFiles pf)
        {
            guestReunion = true;
            EditorSceneManager.SaveOpenScenes();
            SetPhase(TeamSyncPhase.Scanning, "Comparing what you both did while apart...");
            StartScan(list => SendTo(pf, new TeamMessage
            {
                t = "reu",
                // What we last shared with this host, so it can tell what we actually changed while apart.
                m = string.Join("\n", pf.Agreed.Select(pair => pair.Key + "\t" + pair.Value).ToArray())
            }, Encoding.UTF8.GetBytes(WriteManifest(list))));
        }

        /// <summary>Handles the reunion messages. True if the message was one of them.</summary>
        private static bool OnReunionMessage(PeerFiles pf, TeamMessage message, byte[] blob)
        {
            switch (message.t)
            {
                case "reu":
                    if (TeamSession.IsHost && pf != null)
                        HostPlan(pf, blob, message.m);
                    return true;
                case "reuno":
                    // The host has no record of working with us: the normal first-time sync.
                    guestReunion = false;
                    SetPhase(TeamSyncPhase.Scanning, "Asking " + TeamSession.RemoteName + " for the project's file list...");
                    SendTo(pf, new TeamMessage { t = "manreq" });
                    return true;
                case "reuwait":
                    SetPhase(TeamSyncPhase.Scanning, TeamSession.RemoteName + " is looking at what you both changed while apart...");
                    return true;
                case "reufetch":
                    foreach (var path in message.a ?? new string[0])
                    {
                        if (!Shared(path) || !File.Exists(path))
                            continue;
                        string meta = File.Exists(path + ".meta") ? File.ReadAllText(path + ".meta") : string.Empty;
                        SendTo(pf, new TeamMessage { t = "reublob", f = path, m = meta }, File.ReadAllBytes(path));
                    }
                    return true;
                case "reublob":
                    if (TeamSession.IsHost && message.f != null && pendingCopies.ContainsKey(message.f))
                    {
                        ReunionCopyArrived(message.f, blob ?? new byte[0]);
                        return true;
                    }
                    if (TeamSession.IsHost && pf == reunionPeer && message.f != null)
                    {
                        reunionFetched[message.f] = new KeyValuePair<byte[], string>(blob ?? new byte[0], message.m ?? string.Empty);
                        reunionFetching.Remove(message.f);
                        if (reunionFetching.Count == 0)
                            HostFinishPlan();
                    }
                    return true;
                case "reupull":
                    // Send these to the host, made on top of the version we both had.
                    foreach (var path in message.a ?? new string[0])
                    {
                        if (!Shared(path) || !File.Exists(path))
                            continue;
                        string agreed;
                        pf.BaseOf[path] = pf.Agreed.TryGetValue(path, out agreed) ? agreed : string.Empty;
                        Enqueue(pf, path);
                    }
                    return true;
                case "reuexpect":
                    GuestExpect(message.a ?? new string[0]);
                    return true;
                case "reudone":
                    if (TeamSession.IsHost && pf == reunionPeer)
                    {
                        reunionGuestDone = true;
                        HostTryFinish();
                    }
                    return true;
            }
            return false;
        }

        // ---- The host's plan -------------------------------------------------------------------------------------

        private static void HostPlan(PeerFiles pf, byte[] blob, string theirAgreedText)
        {
            var theirs = ReadManifest(blob != null ? Encoding.UTF8.GetString(blob) : string.Empty)
                .Where(e => !e.Dir).ToDictionary(e => e.Path, e => e.Hash);
            // Their record of what we last shared. A change only counts on their side if they made it since then:
            // files of their own they never shared stay theirs, and files they never got aren't "deleted".
            var theirBase = new Dictionary<string, string>();
            foreach (var line in (theirAgreedText ?? string.Empty).Split('\n'))
            {
                int tab = line.IndexOf('\t');
                if (tab > 0)
                    theirBase[line.Substring(0, tab)] = line.Substring(tab + 1);
            }

            if (reunionPeer != null && reunionPeer != pf && pf.Reuniting)
            {
                // Another teammate's merge is running: theirs goes next.
                queuedReunions.RemoveAll(q => q.Peer == pf);
                queuedReunions.Add(new QueuedReunion { Peer = pf, Blob = blob, Agreed = theirAgreedText });
                SendTo(pf, new TeamMessage { t = "reuwait" });
                return;
            }

            if (!pf.Reuniting || pf.ReunionBase == null || pf.ReunionBase.Count == 0)
            {
                // No shared history here (or another reunion is running): the normal first-time sync, host's project wins.
                pf.Reuniting = false;
                StartScan(list =>
                {
                    pf.Agreed.Clear();
                    foreach (var entry in list)
                        pf.Agreed[entry.Path] = entry.Hash;
                    SendTo(pf, new TeamMessage { t = "reuno" });
                });
                return;
            }

            reunionPeer = pf;
            reunionBase = pf.ReunionBase;
            reunionTheirs = theirs;
            reunionFetched.Clear();
            reunionFetching.Clear();
            reunionGuestDone = false;
            ReunionWith = pf.Name;
            SendTo(pf, new TeamMessage { t = "reuwait" });
            EditorSceneManager.SaveOpenScenes();

            StartScan(list =>
            {
                var mine = list.Where(e => !e.Dir).ToDictionary(e => e.Path, e => e.Hash);
                var plan = new List<ReunionItem>();
                var paths = new HashSet<string>(reunionBase.Keys.Concat(mine.Keys).Concat(reunionTheirs.Keys));
                foreach (var path in paths.OrderBy(p => p, StringComparer.Ordinal))
                {
                    if (!Shared(path) || path.EndsWith("/", StringComparison.Ordinal) || Directory.Exists(path))
                        continue;
                    string b, m, t, tb;
                    reunionBase.TryGetValue(path, out b);
                    mine.TryGetValue(path, out m);
                    reunionTheirs.TryGetValue(path, out t);
                    theirBase.TryGetValue(path, out tb);
                    if (b != null && b.StartsWith("dir:", StringComparison.Ordinal))
                        continue;
                    if (m == t)
                        continue;

                    bool mineChanged = m != b;
                    bool theirsChanged = t != tb;
                    var item = new ReunionItem { Path = path };
                    if (!mineChanged && !theirsChanged)
                    {
                        // Neither changed it, yet they differ: a file of theirs they never shared (leave it), or one
                        // of ours they never received (send it, as the first sync would have).
                        if (m == null)
                            continue;
                        item.Action = ReunionAction.SendToThem;
                    }
                    else if (!mineChanged)
                    {
                        if (t == null && tb == null)
                            continue;
                        if (t == null && m != null && IsCode(path))
                        {
                            // Scripts and DLLs they never trusted were never written there: send them again (the trust
                            // prompt still decides), never delete ours because of it.
                            item.Action = ReunionAction.SendToThem;
                            item.Note = "they don't have it (scripts wait for them to trust them)";
                        }
                        else
                            item.Action = t == null ? ReunionAction.DeleteHere : ReunionAction.TakeTheirs;
                    }
                    else if (!theirsChanged)
                        item.Action = m == null ? ReunionAction.DeleteThere : ReunionAction.SendToThem;
                    else if (m == null)
                    {
                        item.Action = ReunionAction.TakeTheirs;
                        item.Note = "you deleted it, they changed it: keeping theirs";
                    }
                    else if (t == null)
                    {
                        item.Action = ReunionAction.SendToThem;
                        item.Note = "they deleted it, you changed it: keeping yours";
                    }
                    else if (b != null && Mergeable(path) && File.Exists(BaseFile(b)) && !LiveWithOthers(path, pf))
                        item.Action = ReunionAction.Merge;
                    else
                    {
                        item.Action = ReunionAction.Conflict;
                        item.Note = LiveWithOthers(path, pf) ? "being edited live with others right now"
                            : b == null ? "you both made a file here" : Mergeable(path) ? "no shared copy to merge from" : "Unity can't merge this kind of file";
                    }
                    plan.Add(item);
                }

                Reunion = plan;
                // Fetch their version of every file both changed, to merge now (so the window shows what clashes).
                foreach (var item in plan.Where(i => i.Action == ReunionAction.Merge))
                    reunionFetching.Add(item.Path);
                if (reunionFetching.Count == 0)
                    HostFinishPlan();
                else
                    SendTo(pf, new TeamMessage { t = "reufetch", a = reunionFetching.ToArray() });
            });
        }

        private static bool LiveWithOthers(string path, PeerFiles except)
        {
            return TeamScene.IsLive(path) && TeamSession.Linked.Any(p => p.Id != except.Id);
        }

        /// <summary>Everything to merge has arrived: merge, then show the window (or sync straight away if nothing's left).</summary>
        private static void HostFinishPlan()
        {
            if (Reunion == null)
                return;
            foreach (var item in Reunion.Where(i => i.Action == ReunionAction.Merge))
            {
                KeyValuePair<byte[], string> theirs;
                if (!reunionFetched.TryGetValue(item.Path, out theirs))
                {
                    item.Action = ReunionAction.Conflict;
                    item.Note = "their copy didn't arrive";
                    continue;
                }
                string temp;
                int result = RunMerge(item.Path, theirs.Key, null, out temp);
                if (result < 0)
                {
                    item.Action = ReunionAction.Conflict;
                    item.Note = "Unity's merge tool couldn't open it";
                    continue;
                }
                item.MergedTemp = temp;
                item.Clashes = result > 0;
                if (item.Clashes)
                    item.Note = "you both changed the same thing in it: pick whose changes win where they clash";
            }

            // No review window yet: sync straight away. Files both changed in the same place keep the host's version
            // (theirs is backed up), everything else merges.
            ExecuteReunion();
        }

        /// <summary>
        /// Merges their copy into ours with Unity's merge tool (object by object; moves, renames, added and deleted
        /// objects included). winner: null to only merge what doesn't clash; Mine/Theirs to settle clashes.
        /// Returns 0 merged cleanly, 1 merged with clashes, -1 failed.
        /// </summary>
        private static int RunMerge(string path, byte[] theirs, ReunionChoice? winner, out string merged)
        {
            merged = null;
            string tool = Path.Combine(EditorApplication.applicationContentsPath, "Tools",
                UnityEngine.Application.platform == UnityEngine.RuntimePlatform.WindowsEditor ? "UnityYAMLMerge.exe" : "UnityYAMLMerge");
            string basePath = BaseFile(reunionBase != null && reunionBase.ContainsKey(path) ? reunionBase[path] : null);
            if (!File.Exists(tool) || basePath == null || !File.Exists(basePath))
                return -1;

            string folder = Path.Combine("Temp", "WPFMATeamMerge");
            Directory.CreateDirectory(folder);
            string ext = Path.GetExtension(path);
            string stem = Path.Combine(folder, Guid.NewGuid().ToString("N"));
            string theirsPath = stem + "-theirs" + ext;
            string minePath = stem + "-mine" + ext;
            string outPath = stem + "-merged" + ext;
            string conflicts = stem + "-conflicts.txt";
            // Objects are recognised by where they are, not by Unity's IDs (which differ between the two editors),
            // so the shared version and theirs take our IDs for every object we have too. See TeamSceneAlign.
            string mineText = File.ReadAllText(path);
            string alignedBase = stem + "-base" + ext;
            File.WriteAllText(alignedBase, TeamSceneAlign.AlignTo(File.ReadAllText(basePath), mineText));
            basePath = alignedBase;
            File.WriteAllBytes(theirsPath, TeamSceneAlign.AlignTo(theirs, mineText));
            File.Copy(path, minePath, true);

            string resolve = winner == ReunionChoice.Mine ? "-r " : winner == ReunionChoice.Theirs ? "-l " : string.Empty;
            var info = new ProcessStartInfo(tool,
                "merge -h --fallback none " + resolve + "-o \"" + conflicts + "\" \"" + basePath + "\" \"" + theirsPath + "\" \"" + minePath + "\" \"" + outPath + "\"")
            {
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };
            try
            {
                using (var process = Process.Start(info))
                {
                    string output = process.StandardOutput.ReadToEnd();
                    string errors = process.StandardError.ReadToEnd();
                    if (!process.WaitForExit(120000))
                    {
                        process.Kill();
                        return -1;
                    }
                    KeepLastMerge(path, basePath, theirsPath, minePath, outPath, conflicts, info.Arguments, process.ExitCode, output + errors);
                    if (!File.Exists(outPath))
                        return -1;
                    merged = outPath;
                    return process.ExitCode == 0 ? 0 : 1;
                }
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA Team] Merging " + path + " failed: " + e.Message);
                return -1;
            }
            finally
            {
                DeleteQuietly(theirsPath);
                DeleteQuietly(minePath);
                DeleteQuietly(basePath);
            }
        }

        /// <summary>
        /// The last merge's files (the shared version, theirs, yours, the result) and what Unity's merge tool said,
        /// in Library/WPFMATeam/last-merge, so a merge that went wrong can be looked into.
        /// </summary>
        private static void KeepLastMerge(string path, string basePath, string theirsPath, string minePath, string outPath, string conflicts,
            string arguments, int exitCode, string output)
        {
            try
            {
                string folder = Path.Combine("Library", "WPFMATeam", "last-merge");
                if (Directory.Exists(folder))
                    Directory.Delete(folder, true);
                Directory.CreateDirectory(folder);
                string ext = Path.GetExtension(path);
                foreach (var pair in new[] { new[] { basePath, "base" }, new[] { theirsPath, "theirs" }, new[] { minePath, "mine" }, new[] { outPath, "merged" } })
                    if (File.Exists(pair[0]))
                        File.Copy(pair[0], Path.Combine(folder, pair[1] + ext), true);
                File.WriteAllText(Path.Combine(folder, "about.txt"), path + "\nexit code " + exitCode + "\nmerge " + arguments + "\n\n" + output +
                    (File.Exists(conflicts) ? "\n\n" + File.ReadAllText(conflicts) : string.Empty));
            }
            catch (Exception)
            {
            }
        }

        // ---- Sync ------------------------------------------------------------------------------------------------

        /// <summary>The host pressed Sync: carry the plan out on both sides.</summary>
        internal static void ExecuteReunion()
        {
            var pf = reunionPeer;
            var plan = Reunion ?? new List<ReunionItem>();
            if (pf == null)
                return;
            Reunion = null;

            var expect = new List<string>();
            var pulls = new List<string>();
            var reload = new List<string>();
            string theirName = pf.Name;

            foreach (var item in plan)
            {
                string theirHash;
                reunionTheirs.TryGetValue(item.Path, out theirHash);
                switch (item.Action)
                {
                    case ReunionAction.TakeTheirs:
                        pulls.Add(item.Path);
                        break;

                    case ReunionAction.DeleteHere:
                        ReceiveDelete(pf, item.Path);
                        break;

                    case ReunionAction.SendToThem:
                        Send(pf, item.Path, theirHash, expect);
                        break;

                    case ReunionAction.DeleteThere:
                        SendTo(pf, new TeamMessage { t = "fdel", f = item.Path });
                        break;

                    case ReunionAction.Merge:
                        string merged = item.MergedTemp;
                        if (item.Clashes)
                        {
                            DeleteQuietly(merged);
                            KeyValuePair<byte[], string> theirs;
                            if (!reunionFetched.TryGetValue(item.Path, out theirs) ||
                                RunMerge(item.Path, theirs.Key, item.Choice == ReunionChoice.Theirs ? ReunionChoice.Theirs : ReunionChoice.Mine, out merged) < 0)
                            {
                                AddRecent("Could not merge " + item.Path + "; kept yours");
                                Send(pf, item.Path, theirHash, expect);
                                break;
                            }
                        }
                        Backup(item.Path);
                        File.Copy(merged, item.Path, true);
                        DeleteQuietly(merged);
                        known.Remove(item.Path);
                        if (TeamScene.IsLoaded(item.Path))
                            reload.Add(item.Path);
                        AssetDatabase.ImportAsset(item.Path, ImportAssetOptions.ForceUpdate);
                        AddRecent("Merged " + item.Path + " (your changes and " + theirName + "'s)");
                        Send(pf, item.Path, theirHash, expect);
                        break;

                    case ReunionAction.Conflict:
                        if (item.Choice == ReunionChoice.Theirs)
                        {
                            reunionAccept.Add(item.Path);
                            pulls.Add(item.Path);
                        }
                        else if (item.Choice == ReunionChoice.Both)
                        {
                            // Keep ours here and there, and theirs next to it as a copy (a new file, so a new GUID).
                            string copy = CopyPathFor(item.Path, theirName);
                            KeyValuePair<byte[], string> fetched;
                            if (reunionFetched.TryGetValue(item.Path, out fetched))
                                WriteCopy(copy, fetched.Key);
                            else
                                SendTo(pf, new TeamMessage { t = "reufetch", a = new[] { item.Path } });
                            pendingCopies[item.Path] = copy;
                            Send(pf, item.Path, theirHash, expect);
                        }
                        else
                            Send(pf, item.Path, theirHash, expect);
                        break;
                }
            }

            foreach (var path in reload)
                ReopenScene(path);

            reunionPulls.Clear();
            foreach (var path in pulls)
                reunionPulls.Add(path);
            SendTo(pf, new TeamMessage { t = "reuexpect", a = expect.ToArray() });
            if (pulls.Count > 0)
                SendTo(pf, new TeamMessage { t = "reupull", a = pulls.ToArray() });
            pf.Reuniting = false;

            AddRecent("Synced with " + theirName + " after working apart: " + plan.Count + " file(s)");
            TeamSession.AddSystem("Synced with " + theirName + ": " + Summary(plan) + ". Anything replaced is backed up in WPFMA-Snapshots/Team.");
            AssetDatabase.Refresh();
            HostTryFinish();
            TeamSession.Raise();
        }

        private static readonly Dictionary<string, string> pendingCopies = new Dictionary<string, string>();
        private static readonly List<string> reopenAfter = new List<string>();

        /// <summary>The teammate left or the session ended mid-reunion: forget it (it starts again when they're back).</summary>
        private static void ResetReunion()
        {
            if (reunionPeer != null)
                reunionPeer.Reuniting = false;
            reunionPeer = null;
            Reunion = null;
            reunionTheirs = null;
            reunionFetched.Clear();
            reunionFetching.Clear();
            reunionAccept.Clear();
            reunionPulls.Clear();
            pendingCopies.Clear();
            queuedReunions.Clear();
            reunionGuestDone = false;
            guestReunion = false;
        }

        private static void Send(PeerFiles pf, string path, string theirHash, List<string> expect)
        {
            if (!File.Exists(path))
                return;
            pf.BaseOf[path] = theirHash ?? string.Empty;
            Enqueue(pf, path, true);
            expect.Add(path);
        }

        private static string CopyPathFor(string path, string name)
        {
            string folder = Path.GetDirectoryName(path) ?? "Assets";
            string stem = Path.GetFileNameWithoutExtension(path) + " (" + WPFMAPaths.SafeFileName(name) + ")";
            string ext = Path.GetExtension(path);
            string copy = Path.Combine(folder, stem + ext).Replace('\\', '/');
            for (int i = 2; File.Exists(copy); i++)
                copy = Path.Combine(folder, stem + " " + i + ext).Replace('\\', '/');
            return copy;
        }

        private static void WriteCopy(string copy, byte[] bytes)
        {
            File.WriteAllBytes(copy, bytes);
            AssetDatabase.ImportAsset(copy);
            AddRecent("Kept their version as " + copy);
        }

        private static void ReopenScene(string path)
        {
            try
            {
                var scene = SceneManager.GetSceneByPath(path);
                if (!scene.IsValid())
                    return;
                bool active = SceneManager.GetActiveScene() == scene;
                if (SceneManager.sceneCount == 1)
                    EditorSceneManager.OpenScene(path, OpenSceneMode.Single);
                else
                {
                    EditorSceneManager.CloseScene(scene, true);
                    var reopened = EditorSceneManager.OpenScene(path, OpenSceneMode.Additive);
                    if (active)
                        SceneManager.SetActiveScene(reopened);
                }
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA Team] Couldn't reopen " + path + " after merging: " + e.Message);
            }
        }

        private static string Summary(List<ReunionItem> plan)
        {
            int incoming = plan.Count(i => i.Action == ReunionAction.TakeTheirs || i.Action == ReunionAction.DeleteHere);
            int outgoing = plan.Count(i => i.Action == ReunionAction.SendToThem || i.Action == ReunionAction.DeleteThere);
            int merged = plan.Count(i => i.Action == ReunionAction.Merge);
            int conflicts = plan.Count(i => i.Action == ReunionAction.Conflict);
            var parts = new List<string>();
            if (incoming > 0) parts.Add(incoming + " from them");
            if (outgoing > 0) parts.Add(outgoing + " to them");
            if (merged > 0) parts.Add(merged + " merged");
            if (conflicts > 0) parts.Add(conflicts + " decided by you");
            return parts.Count == 0 ? "nothing had changed" : string.Join(", ", parts.ToArray());
        }

        /// <summary>Host: a file from the teammate arrived. Copies for "keep both" are written here too.</summary>
        private static void ReunionArrived(string path, string from)
        {
            if (reunionPeer == null || from != reunionPeer.Id)
                return;
            reunionPulls.Remove(path);
            HostTryFinish();
        }

        private sealed class QueuedReunion
        {
            public PeerFiles Peer;
            public byte[] Blob;
            public string Agreed;
        }

        private static readonly List<QueuedReunion> queuedReunions = new List<QueuedReunion>();

        private static void HostTryFinish()
        {
            var pf = reunionPeer;
            if (pf == null || Reunion != null || !reunionGuestDone || reunionPulls.Count > 0)
                return;
            reunionPeer = null;
            // The next teammate waiting to merge (still connected).
            queuedReunions.RemoveAll(q => q.Peer.Peer == null || !q.Peer.Reuniting);
            if (queuedReunions.Count > 0)
            {
                var next = queuedReunions[0];
                queuedReunions.RemoveAt(0);
                EditorApplication.delayCall += () => HostPlan(next.Peer, next.Blob, next.Agreed);
            }
            // Everything matches now: what both have is the new shared version (and its copy, for next time).
            StartScan(list =>
            {
                pf.Agreed.Clear();
                foreach (var entry in list)
                    pf.Agreed[entry.Path] = entry.Hash;
                SaveAgreed(pf);
                CaptureBases(pf, true);
            });
        }

        // Late "keep both" copies (their file came with reufetch after Sync).
        private static void ReunionCopyArrived(string path, byte[] bytes)
        {
            string copy;
            if (pendingCopies.TryGetValue(path, out copy))
            {
                pendingCopies.Remove(path);
                WriteCopy(copy, bytes);
            }
        }

        // ---- The guest's side ------------------------------------------------------------------------------------

        private static void GuestExpect(string[] paths)
        {
            DownloadTotal = 0;
            DownloadDone = 0;
            requested.Clear();
            foreach (var path in paths)
                requested.Add(path);
            if (requested.Count == 0)
            {
                FinishInitial();
                return;
            }
            SetPhase(TeamSyncPhase.Downloading, "Getting " + paths.Length + " file(s) from " + TeamSession.RemoteName + "...");
        }

        /// <summary>Guest: the reunion sync is done. Remember what we both have now, and tell the host.</summary>
        private static void GuestReunionFinished()
        {
            if (!guestReunion)
                return;
            guestReunion = false;
            var pf = For(TeamSession.HostPeer);
            StartScan(list =>
            {
                if (pf == null)
                    return;
                pf.Agreed.Clear();
                foreach (var entry in list)
                {
                    pf.Agreed[entry.Path] = entry.Hash;
                    known[entry.Path] = entry.Hash;
                }
                SaveAgreed(pf);
                CaptureBases(pf, true);
                SendTo(pf, new TeamMessage { t = "reudone" });
            });
        }
    }
}
#endif
