using Azure.Data.Tables; using Microsoft.Extensions.Options; using Tango.Portal.Chat.Web.Models; namespace Tango.Portal.Chat.Web.Services { public sealed class AIInstructionService { private readonly TableClient _tableClient; private readonly ILogger _logger; public AIInstructionService(IOptions options, ILogger logger) { _logger = logger; var serviceClient = new TableServiceClient(options.Value.ConnectionString); _tableClient = serviceClient.GetTableClient("AIInstructions"); // Create table if it doesn't exist _tableClient.CreateIfNotExists(); } public async Task AddInstructionAsync(string instruction, string createdBy) { try { var aiInstruction = new AIInstruction { RowKey = Guid.NewGuid().ToString(), Instruction = instruction, CreatedAt = DateTime.UtcNow, CreatedBy = createdBy }; await _tableClient.AddEntityAsync(aiInstruction); _logger.LogInformation("Added AI instruction by {CreatedBy}: {Instruction}", createdBy, instruction); return true; } catch (Exception ex) { _logger.LogError(ex, "Failed to add AI instruction: {Instruction}", instruction); return false; } } public async Task DeleteLastInstructionAsync() { try { var instructions = await GetAllInstructionsAsync(); var lastInstruction = instructions.OrderByDescending(i => i.CreatedAt).FirstOrDefault(); if (lastInstruction == null) { _logger.LogWarning("No instructions found to delete"); return false; } await _tableClient.DeleteEntityAsync(lastInstruction.PartitionKey, lastInstruction.RowKey); _logger.LogInformation("Deleted last AI instruction: {Instruction}", lastInstruction.Instruction); return true; } catch (Exception ex) { _logger.LogError(ex, "Failed to delete last AI instruction"); return false; } } public async Task> GetAllInstructionsAsync() { try { var instructions = new List(); await foreach (var instruction in _tableClient.QueryAsync()) { instructions.Add(instruction); } return instructions.OrderBy(i => i.CreatedAt).ToList(); } catch (Exception ex) { _logger.LogError(ex, "Failed to retrieve AI instructions"); return new List(); } } public async Task GetInstructionsTextAsync() { var instructions = await GetAllInstructionsAsync(); if (!instructions.Any()) return string.Empty; var instructionTexts = instructions.Select(i => i.Instruction); return string.Join("\n", instructionTexts); } } }