using System.Text.Json;

public static class MalwareReportLoader
{
    public static MalwareIndicators NormalizeIocs(string family, string? sampleId, Ethanol.MalwareSonar.MalwareReport.Iocs? source)
    {
        return new MalwareIndicators
        (
            family,
            sampleId ?? string.Empty,
            source?.Urls?.Select(url => url.StartsWith("http://") ? url["http://".Length..] : url).ToArray() ?? Array.Empty<string>(),
            source?.Domains ?? Array.Empty<string>(),
            source?.Ips ?? Array.Empty<string>()
        );
    }

    public static IEnumerable<Ethanol.MalwareSonar.MalwareReport.Report> LoadAllReports(string rootFolder)
    {
        var families = Directory.GetDirectories(rootFolder);
        foreach (var family in families)
        {
            var familyName = Path.GetFileName(family);
            var samples = Directory.GetFiles(family);
            foreach (var sample in samples)
            {
                var report = JsonSerializer.Deserialize<Ethanol.MalwareSonar.MalwareReport.Report>(File.ReadAllText(sample));
                if (report != null && report.Sample != null && report.Targets != null)
                {
                    yield return report;
                }
            }
        }
    }
    public static IEnumerable<Ethanol.MalwareSonar.MalwareReport.Report> LoadFamilyReports(string rootFamilyFolder)
    {
        var samples = Directory.GetFiles(rootFamilyFolder);
        foreach (var sample in samples)
        {
            var report = JsonSerializer.Deserialize<Ethanol.MalwareSonar.MalwareReport.Report>(File.ReadAllText(sample));
            if (report != null && report.Sample != null && report.Targets != null)
            {
                yield return report;
            }
        }
    }

    public static Ethanol.MalwareSonar.MalwareReport.Report? LoadReport(string path) => JsonSerializer.Deserialize<Ethanol.MalwareSonar.MalwareReport.Report>(File.ReadAllText(path));

    public static IEnumerable<MalwareIndicators> GetMalwareIndicators(string familyName, IEnumerable<Ethanol.MalwareSonar.MalwareReport.Report> reports)
    {
        return reports.SelectMany(report => report?.Targets?.Select(t => NormalizeIocs(familyName, report.Sample?.Id ?? String.Empty, t.Iocs))??Enumerable.Empty<MalwareIndicators>());
    }
}



