using System.Text.Json;
using QuantEngine.Core.Interfaces;

namespace QuantEngine.Application.Services;

public sealed class LearningDatasetService
{
    private readonly ILearningDatasetReader _reader;

    public LearningDatasetService(ILearningDatasetReader reader) => _reader = reader;

    public async Task<string> ExportJsonAsync(string outputPath, int limit = 1000)
    {
        var normalizedOutputPath = RequireValue(outputPath, nameof(outputPath));
        var normalizedLimit = Math.Clamp(limit, 1, 10000);
        var rows = await _reader.ReadTrainingExamplesAsync(normalizedLimit);
        var payload = new
        {
            formula_id = "ENGINE_HISTORY_TRAINING_DATASET_V1",
            gate = rows.Count > 0 ? "PASS" : "DATA_MISSING",
            generated_at = DateTimeOffset.UtcNow,
            sample_count = rows.Count,
            source = "engine_history.training_example_v1",
            rows
        };
        var path = Path.GetFullPath(normalizedOutputPath);
        Directory.CreateDirectory(Path.GetDirectoryName(path)!);
        await File.WriteAllTextAsync(path, JsonSerializer.Serialize(payload, new JsonSerializerOptions { WriteIndented = true }));
        return path;
    }

    private static string RequireValue(string value, string parameterName)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            throw new ArgumentException("Value is required.", parameterName);
        }

        return value.Trim();
    }
}
