using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using AIRuntime.Runtime.Filesystem;
using AIRuntime.Runtime.Providers.Testing;
using AIRuntime.Runtime.Services.Agent;
using UnityEngine;

namespace AIRuntime.Runtime.Examples
{
    public sealed class OfflineToolLoop : MonoBehaviour
    {
        private string _status = "Press Run to exercise a scripted provider and one real file-read tool.";
        private bool _running;
        private void OnGUI()
        {
            GUILayout.BeginArea(new Rect(24, 24, Mathf.Max(300, Screen.width - 48), 240), GUI.skin.box);
            GUILayout.Label("AIRuntime — Offline Tool Loop");
            GUILayout.Label("No model, credentials or network required. This demonstrates orchestration, not live inference.");
            GUI.enabled = !_running;
            if (GUILayout.Button("Run offline demo", GUILayout.Height(36))) RunDemo();
            GUI.enabled = true;
            GUILayout.Label(_status);
            GUILayout.EndArea();
        }
        private async void RunDemo()
        {
            _running = true;
            try { var result = await RunAsync(); _status = "PASS: " + result.Response + " | Tool calls: " + result.ToolCallsExecuted; }
            catch (Exception e) { _status = "Failed: " + e.Message; Debug.LogException(e); }
            finally { _running = false; }
        }

        // A scripted provider demonstrates dispatch without a model, key or network call.
        public static async Task<AgentRunResult> RunAsync()
        {
            string workspace = Path.Combine(Path.GetTempPath(), "AIRuntimeExample", Guid.NewGuid().ToString("N"));
            Directory.CreateDirectory(workspace);
            try
            {
                File.WriteAllText(Path.Combine(workspace, "test.txt"), "Hello from AIRuntime.");
                var runtime = new AIRuntime(workspace);
                runtime.RegisterCapability(new ReadFileCapability());
                runtime.UseProvider(new FakeProvider());
                using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15)))
                {
                    AgentRunResult result = await runtime.RunAsync("Read test.txt", timeout.Token);
                    if (!result.Succeeded || result.ToolCallsExecuted != 1)
                        throw new InvalidOperationException("Offline example failed: " + result.Status + " " + result.ErrorMessage);
                    Debug.Log("AIRuntime offline example PASS: " + result.Response + " (1 tool call)");
                    return result;
                }
            }
            finally { Directory.Delete(workspace, true); }
        }
    }
}
