using System.Collections.Generic;
using System.Text.Json;

namespace TestersAI;

public sealed class AnalysisResult
{
    public string Kind { get; init; } = "";
    public bool Ok { get; set; } = true;
    public bool Skipped { get; set; }
    public string? Reason { get; set; }
    public string? Error { get; set; }
    public int DurationMs { get; set; }
    public List<Issue> Issues { get; } = new();
    public string? Raw { get; set; }

    public bool Failed
    {
        get
        {
            foreach (var i in Issues)
                if (i.Severity == "high" || i.Severity == "critical") return true;
            return false;
        }
    }

    internal static AnalysisResult Skipped(string kind, string reason, string? error, int ms)
        => new() { Kind = kind, Skipped = true, Reason = reason, Error = error, DurationMs = ms, Ok = error is null };

    internal static AnalysisResult Parse(string kind, string body, int ms)
    {
        var r = new AnalysisResult { Kind = kind, DurationMs = ms, Raw = body };
        try
        {
            using var doc = JsonDocument.Parse(body);
            if (doc.RootElement.TryGetProperty("issues", out var arr) && arr.ValueKind == JsonValueKind.Array)
            {
                foreach (var el in arr.EnumerateArray())
                {
                    r.Issues.Add(new Issue
                    {
                        Severity = el.TryGetProperty("severity", out var s) ? s.GetString() ?? "info" : "info",
                        Category = el.TryGetProperty("category", out var c) ? c.GetString() ?? "general" : "general",
                        Message = el.TryGetProperty("message", out var m) ? m.GetString() ?? "" : "",
                        Location = el.TryGetProperty("location", out var l) ? l.GetString() : null,
                        Evidence = el.TryGetProperty("evidence", out var e) ? e.GetString() : null,
                    });
                }
            }
        }
        catch { /* best-effort parse */ }
        return r;
    }

    public sealed class Issue
    {
        public string Severity { get; set; } = "info";
        public string Category { get; set; } = "general";
        public string Message { get; set; } = "";
        public string? Location { get; set; }
        public string? Evidence { get; set; }
    }
}
