// ============================================================
// MS AGENT FRAMEWORK TEMPLATE
// Generated by MORPH Framework
// ============================================================

using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
using System.Text.Json;

namespace MyProject.Agents.{Feature}Analyzer;

/// <summary>
/// AI Agent for analyzing {Feature} data.
/// Uses Semantic Kernel with Azure OpenAI (gpt-4o-mini by default).
/// </summary>
public class {Feature}AnalyzerAgent(
    Kernel kernel,
    ILogger<{Feature}AnalyzerAgent> logger) : I{Feature}AnalyzerAgent
{
    private const int MaxRetries = 3;
    private static readonly TimeSpan[] RetryDelays =
    {
        TimeSpan.FromSeconds(1),
        TimeSpan.FromSeconds(2),
        TimeSpan.FromSeconds(4)
    };

    /// <inheritdoc />
    public async Task<{Feature}AnalysisResult> AnalyzeAsync(
        {Feature}Data data,
        CancellationToken cancellationToken = default)
    {
        logger.LogInformation("Starting {Feature} analysis for: {Content}",
            data.Content.Length > 100 ? data.Content[..100] + "..." : data.Content);

        var prompt = BuildPrompt(data);

        for (int attempt = 0; attempt < MaxRetries; attempt++)
        {
            try
            {
                var response = await kernel.InvokePromptAsync(
                    prompt,
                    cancellationToken: cancellationToken);

                var result = ParseResponse(response.ToString());

                logger.LogInformation(
                    "Analysis completed. Confidence: {Confidence:P0}",
                    result.ConfidenceScore);

                return result;
            }
            catch (Exception ex) when (attempt < MaxRetries - 1)
            {
                logger.LogWarning(ex,
                    "Analysis attempt {Attempt} failed, retrying...",
                    attempt + 1);

                await Task.Delay(RetryDelays[attempt], cancellationToken);
            }
        }

        throw new {Feature}ProcessingException("Analysis failed after all retries");
    }

    #region Private Methods

    private static string BuildPrompt({Feature}Data data)
    {
        return $"""
            You are an expert analyst for {Feature} data.

            Analyze the following data and provide insights:

            <data>
            {data.Content}
            </data>

            Provide your analysis in the following JSON format:
            {{
                "summary": "Brief summary of the analysis (1-2 sentences)",
                "insights": ["insight 1", "insight 2", "insight 3"],
                "recommendations": ["recommendation 1", "recommendation 2"],
                "confidenceScore": 0.85
            }}

            Guidelines:
            - Be concise and actionable
            - Confidence score should be between 0 and 1
            - Provide at least 2 insights
            - Provide at least 1 recommendation
            - Focus on practical, business-relevant observations

            Respond ONLY with the JSON object, no additional text.
            """;
    }

    private {Feature}AnalysisResult ParseResponse(string response)
    {
        try
        {
            // Clean up response (remove markdown code blocks if present)
            var json = response
                .Replace("```json", "")
                .Replace("```", "")
                .Trim();

            var parsed = JsonSerializer.Deserialize<AnalysisResponse>(json,
                new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

            if (parsed is null)
            {
                throw new {Feature}ProcessingException("Failed to parse analysis response");
            }

            return new {Feature}AnalysisResult(
                parsed.Summary ?? "Analysis completed",
                parsed.Insights ?? new List<string>(),
                parsed.Recommendations ?? new List<string>(),
                parsed.ConfidenceScore
            );
        }
        catch (JsonException ex)
        {
            logger.LogError(ex, "Failed to parse AI response: {Response}", response);
            throw new {Feature}ProcessingException("Failed to parse analysis response", ex);
        }
    }

    private class AnalysisResponse
    {
        public string? Summary { get; set; }
        public List<string>? Insights { get; set; }
        public List<string>? Recommendations { get; set; }
        public double ConfidenceScore { get; set; }
    }

    #endregion
}

// ============================================================
// DEPENDENCY INJECTION SETUP
// ============================================================
//
// In Program.cs or a DI extension:
//
// public static IServiceCollection AddAgents(
//     this IServiceCollection services,
//     IConfiguration configuration)
// {
//     // Configure Semantic Kernel with Azure OpenAI
//     var builder = Kernel.CreateBuilder();
//
//     builder.AddAzureOpenAIChatCompletion(
//         deploymentName: "gpt-4o-mini",
//         endpoint: configuration["AzureOpenAI:Endpoint"]!,
//         apiKey: configuration["AzureOpenAI:ApiKey"]!);
//
//     // Or with Managed Identity (preferred):
//     // builder.AddAzureOpenAIChatCompletion(
//     //     deploymentName: "gpt-4o-mini",
//     //     endpoint: configuration["AzureOpenAI:Endpoint"]!,
//     //     credentials: new DefaultAzureCredential());
//
//     services.AddSingleton(builder.Build());
//     services.AddScoped<I{Feature}AnalyzerAgent, {Feature}AnalyzerAgent>();
//
//     return services;
// }
//
// ============================================================
