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

namespace QuantEngine.Application.Services;

public sealed class RuntimeAuditTrailService : IRuntimeAuditTrailService
{
    private readonly string _auditRoot;

    public RuntimeAuditTrailService()
    {
        _auditRoot = FindRepoTempRoot();
    }

    public void Append<T>(string category, string key, T payload)
    {
        var root = Path.Combine(_auditRoot, category);
        Directory.CreateDirectory(root);
        var path = Path.Combine(root, $"{key}.jsonl");
        File.AppendAllText(path, JsonSerializer.Serialize(payload, new JsonSerializerOptions { WriteIndented = false }) + Environment.NewLine);
    }

    private static string FindRepoTempRoot()
    {
        var current = new DirectoryInfo(AppContext.BaseDirectory);
        while (current != null)
        {
            if (Directory.Exists(Path.Combine(current.FullName, ".git")))
            {
                return Path.Combine(current.FullName, "Temp");
            }
            current = current.Parent;
        }

        return Path.Combine(Directory.GetCurrentDirectory(), "Temp");
    }
}
