using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

using AIRuntime.Runtime.Models;
using AIRuntime.Runtime.Providers;
using AIRuntime.Runtime.Providers.Models;
using AIRuntime.Runtime.Services.Agent;

using NUnit.Framework;

using UnityEngine;
using UnityEngine.TestTools;


namespace AIRuntime.Tests
{
    public sealed class AgentConcurrencyTests
    {
        private string _workspace;


        [SetUp]
        public void Setup()
        {
            _workspace =
                Path.Combine(
                    Application.temporaryCachePath,
                    "AIRuntimeAgentConcurrencyTests");


            if (Directory.Exists(_workspace))
            {
                Directory.Delete(
                    _workspace,
                    true);
            }


            Directory.CreateDirectory(
                _workspace);
        }


        [TearDown]
        public void Cleanup()
        {
            if (Directory.Exists(_workspace))
            {
                Directory.Delete(
                    _workspace,
                    true);
            }
        }


        //--------------------------------------------------
        // Concurrent Chat Rejection
        //--------------------------------------------------

        [UnityTest]
        public IEnumerator ConcurrentChatRun_IsRejected()
        {
            BlockingProvider provider =
                new BlockingProvider();


            AIRuntime.Runtime.AIRuntime runtime =
                CreateRuntime(
                    provider);


            using CancellationTokenSource cancellation =
                new CancellationTokenSource();


            Task<string> firstTask =
                runtime.ChatAsync(
                    "First run.",
                    cancellation.Token);


            while (!provider.HasStarted)
            {
                yield return null;
            }


            Task<string> secondTask =
                runtime.ChatAsync(
                    "Second run.");


            yield return WaitForTask(
                secondTask);


            Assert.IsTrue(
                secondTask.IsFaulted,
                "A concurrent ChatAsync request should be rejected.");


            Exception exception =
                UnwrapException(
                    secondTask.Exception);


            Assert.IsInstanceOf<InvalidOperationException>(
                exception);


            Assert.AreEqual(
                "An agent run is already in progress.",
                exception.Message);


            cancellation.Cancel();


            yield return WaitForTask(
                firstTask);


            Assert.IsTrue(
                firstTask.IsCanceled);
        }


        //--------------------------------------------------
        // Structured Concurrent Rejection
        //--------------------------------------------------

        [UnityTest]
        public IEnumerator ConcurrentStructuredRun_ReturnsFailureResult()
        {
            BlockingProvider provider =
                new BlockingProvider();


            AIRuntime.Runtime.AIRuntime runtime =
                CreateRuntime(
                    provider);


            using CancellationTokenSource cancellation =
                new CancellationTokenSource();


            Task<string> firstTask =
                runtime.ChatAsync(
                    "First run.",
                    cancellation.Token);


            while (!provider.HasStarted)
            {
                yield return null;
            }


            AgentRunContext activeContext =
                runtime.LastRunContext;


            Task<AgentRunResult> secondTask =
                runtime.RunAsync(
                    "Second run.");


            yield return WaitForTask(
                secondTask);


            AssertTaskCompletedSuccessfully(
                secondTask,
                "Concurrent structured run");


            AgentRunResult result =
                secondTask.GetAwaiter()
                    .GetResult();


            Assert.IsFalse(
                result.Succeeded);


            Assert.IsFalse(
                result.Cancelled);


            Assert.IsFalse(
                result.TimedOut);


            Assert.AreEqual(
                "An agent run is already in progress.",
                result.ErrorMessage);


            Assert.IsFalse(
                string.IsNullOrWhiteSpace(
                    result.SessionId));


            Assert.AreNotEqual(
                activeContext.SessionId,
                result.SessionId);


            Assert.AreEqual(
                0,
                result.ToolCallsExecuted);


            Assert.AreSame(
                activeContext,
                runtime.LastRunContext);


            cancellation.Cancel();


            yield return WaitForTask(
                firstTask);


            Assert.IsTrue(
                firstTask.IsCanceled);
        }


        //--------------------------------------------------
        // Running State
        //--------------------------------------------------

        [UnityTest]
        public IEnumerator IsRunning_IsTrueDuringExecution()
        {
            BlockingProvider provider =
                new BlockingProvider();


            AIRuntime.Runtime.AIRuntime runtime =
                CreateRuntime(
                    provider);


            using CancellationTokenSource cancellation =
                new CancellationTokenSource();


            Task<string> task =
                runtime.ChatAsync(
                    "Block until cancelled.",
                    cancellation.Token);


            while (!provider.HasStarted)
            {
                yield return null;
            }


            Assert.IsTrue(
                runtime.IsRunning);


            cancellation.Cancel();


            yield return WaitForTask(
                task);


            Assert.IsFalse(
                runtime.IsRunning);
        }


        [UnityTest]
        public IEnumerator IsRunning_ReturnsFalseAfterSuccess()
        {
            AIRuntime.Runtime.AIRuntime runtime =
                CreateRuntime(
                    new SuccessfulProvider());


            Task<string> task =
                runtime.ChatAsync(
                    "Complete successfully.");


            yield return WaitForTask(
                task);


            AssertTaskCompletedSuccessfully(
                task,
                "Successful run");


            Assert.IsFalse(
                runtime.IsRunning);
        }


        [UnityTest]
        public IEnumerator IsRunning_ReturnsFalseAfterCancellation()
        {
            BlockingProvider provider =
                new BlockingProvider();


            AIRuntime.Runtime.AIRuntime runtime =
                CreateRuntime(
                    provider);


            using CancellationTokenSource cancellation =
                new CancellationTokenSource();


            Task<AgentRunResult> task =
                runtime.RunAsync(
                    "Cancel this run.",
                    cancellation.Token);


            while (!provider.HasStarted)
            {
                yield return null;
            }


            Assert.IsTrue(
                runtime.IsRunning);


            cancellation.Cancel();


            yield return WaitForTask(
                task);


            AssertTaskCompletedSuccessfully(
                task,
                "Cancelled structured run");


            Assert.IsFalse(
                runtime.IsRunning);
        }


        [UnityTest]
        public IEnumerator IsRunning_ReturnsFalseAfterTimeout()
        {
            AIRuntime.Runtime.AIRuntime runtime =
                CreateRuntime(
                    new BlockingProvider());


            runtime.ProviderTimeout =
                TimeSpan.FromMilliseconds(
                    100);


            Task<AgentRunResult> task =
                runtime.RunAsync(
                    "Allow this run to time out.");


            Assert.IsTrue(
                runtime.IsRunning);


            yield return WaitForTask(
                task);


            AssertTaskCompletedSuccessfully(
                task,
                "Timed-out structured run");


            AgentRunResult result =
                task.GetAwaiter()
                    .GetResult();


            Assert.IsTrue(
                result.TimedOut);


            Assert.IsFalse(
                runtime.IsRunning);
        }


        [UnityTest]
        public IEnumerator IsRunning_ReturnsFalseAfterFailure()
        {
            AIRuntime.Runtime.AIRuntime runtime =
                CreateRuntime(
                    new FailingProvider());


            Task<AgentRunResult> task =
                runtime.RunAsync(
                    "Fail this run.");


            yield return WaitForTask(
                task);


            AssertTaskCompletedSuccessfully(
                task,
                "Failed structured run");


            AgentRunResult result =
                task.GetAwaiter()
                    .GetResult();


            Assert.IsFalse(
                result.Succeeded);


            Assert.IsFalse(
                runtime.IsRunning);
        }


        //--------------------------------------------------
        // Conversation Protection
        //--------------------------------------------------

        [UnityTest]
        public IEnumerator RejectedRun_DoesNotModifyConversation()
        {
            BlockingProvider provider =
                new BlockingProvider();


            AIRuntime.Runtime.AIRuntime runtime =
                CreateRuntime(
                    provider);


            using CancellationTokenSource cancellation =
                new CancellationTokenSource();


            Task<string> firstTask =
                runtime.ChatAsync(
                    "Active prompt.",
                    cancellation.Token);


            while (!provider.HasStarted)
            {
                yield return null;
            }


            Assert.AreEqual(
                1,
                runtime.MessageCount);


            Task<AgentRunResult> rejectedTask =
                runtime.RunAsync(
                    "Rejected prompt.");


            yield return WaitForTask(
                rejectedTask);


            AssertTaskCompletedSuccessfully(
                rejectedTask,
                "Rejected structured run");


            AgentRunResult result =
                rejectedTask.GetAwaiter()
                    .GetResult();


            Assert.IsFalse(
                result.Succeeded);


            Assert.AreEqual(
                "An agent run is already in progress.",
                result.ErrorMessage);


            Assert.AreEqual(
                1,
                runtime.MessageCount,
                "The rejected run must not add a conversation message.");


            cancellation.Cancel();


            yield return WaitForTask(
                firstTask);


            Assert.AreEqual(
                0,
                runtime.MessageCount,
                "The cancelled active run should roll back its prompt.");
        }


        //--------------------------------------------------
        // State Mutation Protection
        //--------------------------------------------------

        [UnityTest]
        public IEnumerator ResetConversation_DuringRun_IsRejected()
        {
            BlockingProvider provider =
                new BlockingProvider();


            AIRuntime.Runtime.AIRuntime runtime =
                CreateRuntime(
                    provider);


            using CancellationTokenSource cancellation =
                new CancellationTokenSource();


            Task<string> task =
                runtime.ChatAsync(
                    "Active run.",
                    cancellation.Token);


            while (!provider.HasStarted)
            {
                yield return null;
            }


            InvalidOperationException exception =
                Assert.Throws<InvalidOperationException>(
                    runtime.ResetConversation);


            Assert.AreEqual(
                "The conversation cannot be reset while an agent run is in progress.",
                exception.Message);


            Assert.AreEqual(
                1,
                runtime.MessageCount);


            cancellation.Cancel();


            yield return WaitForTask(
                task);
        }


        [UnityTest]
        public IEnumerator ProviderSwitch_DuringRun_IsRejected()
        {
            BlockingProvider provider =
                new BlockingProvider();


            AIRuntime.Runtime.AIRuntime runtime =
                CreateRuntime(
                    provider);


            using CancellationTokenSource cancellation =
                new CancellationTokenSource();


            Task<string> task =
                runtime.ChatAsync(
                    "Active run.",
                    cancellation.Token);


            while (!provider.HasStarted)
            {
                yield return null;
            }


            InvalidOperationException exception =
                Assert.Throws<InvalidOperationException>(
                    () =>
                    {
                        runtime.UseProvider(
                            new SuccessfulProvider());
                    });


            Assert.AreEqual(
                "Provider configuration cannot be changed while an agent run is in progress.",
                exception.Message);


            Assert.IsTrue(
                runtime.IsRunning);


            cancellation.Cancel();


            yield return WaitForTask(
                task);


            Assert.IsFalse(
                runtime.IsRunning);
        }


        //--------------------------------------------------
        // Runtime Creation
        //--------------------------------------------------

        private AIRuntime.Runtime.AIRuntime CreateRuntime(
            IProvider provider)
        {
            AIRuntime.Runtime.AIRuntime runtime =
                new AIRuntime.Runtime.AIRuntime(
                    _workspace);


            runtime.UseProvider(
                provider);


            return runtime;
        }


        //--------------------------------------------------
        // Test Providers
        //--------------------------------------------------

        private sealed class BlockingProvider :
            IProvider
        {
            public string Name =>
                "BlockingProvider";


            public bool HasStarted
            {
                get;
                private set;
            }


            public async Task<ChatCompletion> ChatAsync(
                IReadOnlyList<ConversationMessage> messages,
                IReadOnlyList<ProviderTool> tools,
                CancellationToken cancellationToken = default)
            {
                HasStarted =
                    true;


                await Task.Delay(
                    Timeout.Infinite,
                    cancellationToken);


                throw new InvalidOperationException(
                    "The blocking provider should not finish normally.");
            }
        }


        private sealed class SuccessfulProvider :
            IProvider
        {
            public string Name =>
                "SuccessfulProvider";


            public Task<ChatCompletion> ChatAsync(
                IReadOnlyList<ConversationMessage> messages,
                IReadOnlyList<ProviderTool> tools,
                CancellationToken cancellationToken = default)
            {
                cancellationToken
                    .ThrowIfCancellationRequested();


                return Task.FromResult(
                    new ChatCompletion
                    {
                        Content =
                            "Successful response."
                    });
            }
        }


        private sealed class FailingProvider :
            IProvider
        {
            public string Name =>
                "FailingProvider";


            public Task<ChatCompletion> ChatAsync(
                IReadOnlyList<ConversationMessage> messages,
                IReadOnlyList<ProviderTool> tools,
                CancellationToken cancellationToken = default)
            {
                cancellationToken
                    .ThrowIfCancellationRequested();


                throw new InvalidOperationException(
                    "Simulated provider failure.");
            }
        }


        //--------------------------------------------------
        // Coroutine Helpers
        //--------------------------------------------------

        private static IEnumerator WaitForTask(
            Task task)
        {
            while (!task.IsCompleted)
            {
                yield return null;
            }
        }


        //--------------------------------------------------
        // Assertion Helpers
        //--------------------------------------------------

        private static void AssertTaskCompletedSuccessfully(
            Task task,
            string operation)
        {
            Assert.IsNotNull(
                task,
                operation + " returned a null task.");


            if (task.IsCanceled)
            {
                Assert.Fail(
                    operation +
                    " was unexpectedly cancelled.");
            }


            if (!task.IsFaulted)
                return;


            Exception exception =
                UnwrapException(
                    task.Exception);


            Assert.Fail(
                operation +
                " failed:\n" +
                (exception?.ToString() ??
                 "Unknown task failure."));
        }


        private static Exception UnwrapException(
            Exception exception)
        {
            if (!(exception is AggregateException aggregate))
                return exception;


            AggregateException flattened =
                aggregate.Flatten();


            if (flattened.InnerExceptions.Count == 1)
            {
                return flattened.InnerExceptions[0];
            }


            return flattened;
        }
    }
}
