using System.Globalization;
using System.Runtime.CompilerServices;
using Wickra;
using Xunit;

namespace Wickra.Tests;

/// <summary>
/// Golden-fixture parity: replay the shared <c>testdata/golden</c> input series
/// through the C# FFI and assert every value matches the Rust reference output.
/// Where the archetype tests only check finiteness, this pins exact values, so a
/// wiring bug (swapped parameter, wrong multi-output field) is caught.
/// Fixtures are generated by <c>cargo run -p wickra-examples --bin gen_golden</c>.
/// </summary>
public class GoldenTests
{
    private const double Tol = 1e-6;

    private static string GoldenDir([CallerFilePath] string file = "") =>
        Path.GetFullPath(Path.Combine(Path.GetDirectoryName(file)!, "..", "..", "..", "testdata", "golden"));

    private static List<string[]> ReadCsv(string name)
    {
        var path = Path.Combine(GoldenDir(), name + ".csv");
        return File.ReadAllLines(path)
            .Skip(1) // header
            .Where(l => l.Length > 0)
            .Select(l => l.Split(','))
            .ToList();
    }

    private static double[][] Input()
    {
        return ReadCsv("input")
            .Select(r => r.Select(c => double.Parse(c, CultureInfo.InvariantCulture)).ToArray())
            .ToArray();
    }

    private static double Cell(string s) =>
        s == "nan" ? double.NaN : double.Parse(s, CultureInfo.InvariantCulture);

    private static void AssertClose(double got, double want, int row, string field)
    {
        if (double.IsNaN(want))
        {
            Assert.True(double.IsNaN(got), $"row {row} {field}: expected warmup/NaN, got {got}");
            return;
        }
        var tol = Tol * Math.Max(1.0, Math.Abs(want));
        Assert.True(Math.Abs(got - want) <= tol, $"row {row} {field}: got {got}, want {want}");
    }

    // --- scalar (close-driven) ------------------------------------------------

    [Theory]
    [InlineData("sma")]
    [InlineData("ema")]
    [InlineData("rsi")]
    public void Scalar_MatchesGolden(string name)
    {
        var input = Input();
        var expected = ReadCsv(name);
        using var ind = (IDisposable)(name switch
        {
            "sma" => new Sma(14),
            "ema" => new Ema(14),
            "rsi" => new Rsi(14),
            _ => throw new ArgumentOutOfRangeException(nameof(name)),
        });
        for (var i = 0; i < input.Length; i++)
        {
            var close = input[i][3];
            double got = ind switch
            {
                Sma s => s.Update(close),
                Ema e => e.Update(close),
                Rsi r => r.Update(close),
                _ => double.NaN,
            };
            AssertClose(got, Cell(expected[i][0]), i, name);
        }
    }

    // --- candle, single output ------------------------------------------------

    [Fact]
    public void Candle_Atr_MatchesGolden()
    {
        var input = Input();
        var expected = ReadCsv("atr");
        using var atr = new Atr(14);
        for (var i = 0; i < input.Length; i++)
        {
            var (o, h, l, c, v) = (input[i][0], input[i][1], input[i][2], input[i][3], input[i][4]);
            AssertClose(atr.Update(o, h, l, c, v, i), Cell(expected[i][0]), i, "atr");
        }
    }

    // --- pairwise -------------------------------------------------------------

    [Fact]
    public void Pairwise_Beta_MatchesGolden()
    {
        var input = Input();
        var expected = ReadCsv("beta");
        using var beta = new Beta(20);
        for (var i = 0; i < input.Length; i++)
        {
            // generator fed (close, open)
            AssertClose(beta.Update(input[i][3], input[i][0]), Cell(expected[i][0]), i, "beta");
        }
    }

    // --- scalar multi-output: MACD -------------------------------------------

    [Fact]
    public void MultiOutput_Macd_MatchesGolden()
    {
        var input = Input();
        var expected = ReadCsv("macd");
        using var macd = new MacdIndicator(12, 26, 9);
        for (var i = 0; i < input.Length; i++)
        {
            MacdOutput? got = macd.Update(input[i][3]);
            var e = expected[i];
            if (e[0] == "nan")
            {
                Assert.Null(got);
                continue;
            }
            Assert.NotNull(got);
            AssertClose(got!.Value.Macd, Cell(e[0]), i, "macd.macd");
            AssertClose(got.Value.Signal, Cell(e[1]), i, "macd.signal");
            AssertClose(got.Value.Histogram, Cell(e[2]), i, "macd.histogram");
        }
    }

    // --- candle multi-output: ADX --------------------------------------------

    [Fact]
    public void MultiOutput_Adx_MatchesGolden()
    {
        var input = Input();
        var expected = ReadCsv("adx");
        using var adx = new Adx(14);
        for (var i = 0; i < input.Length; i++)
        {
            var (o, h, l, c, v) = (input[i][0], input[i][1], input[i][2], input[i][3], input[i][4]);
            AdxOutput? got = adx.Update(o, h, l, c, v, i);
            var e = expected[i];
            if (e[0] == "nan")
            {
                Assert.Null(got);
                continue;
            }
            Assert.NotNull(got);
            AssertClose(got!.Value.PlusDi, Cell(e[0]), i, "adx.plus_di");
            AssertClose(got.Value.MinusDi, Cell(e[1]), i, "adx.minus_di");
            AssertClose(got.Value.Adx, Cell(e[2]), i, "adx.adx");
        }
    }

    // --- the four de-duplicated indicators ------------------------------------

    [Fact]
    public void Candle_AdOscillator_MatchesGolden()
    {
        var input = Input();
        var expected = ReadCsv("ad_oscillator");
        using var ad = new AdOscillator();
        for (var i = 0; i < input.Length; i++)
        {
            var (o, h, l, c, v) = (input[i][0], input[i][1], input[i][2], input[i][3], input[i][4]);
            AssertClose(ad.Update(o, h, l, c, v, i), Cell(expected[i][0]), i, "ad_oscillator");
        }
    }

    [Fact]
    public void Candle_IntradayIntensity_MatchesGolden()
    {
        var input = Input();
        var expected = ReadCsv("intraday_intensity");
        using var ii = new IntradayIntensity();
        for (var i = 0; i < input.Length; i++)
        {
            var (o, h, l, c, v) = (input[i][0], input[i][1], input[i][2], input[i][3], input[i][4]);
            AssertClose(ii.Update(o, h, l, c, v, i), Cell(expected[i][0]), i, "intraday_intensity");
        }
    }

    [Fact]
    public void Candle_AwesomeOscillatorHistogram_MatchesGolden()
    {
        var input = Input();
        var expected = ReadCsv("awesome_oscillator_histogram");
        using var aoh = new AwesomeOscillatorHistogram(5, 34, 1);
        for (var i = 0; i < input.Length; i++)
        {
            var (o, h, l, c, v) = (input[i][0], input[i][1], input[i][2], input[i][3], input[i][4]);
            AssertClose(aoh.Update(o, h, l, c, v, i), Cell(expected[i][0]), i, "awesome_oscillator_histogram");
        }
    }

    [Fact]
    public void Scalar_AverageDrawdown_MatchesGolden()
    {
        var input = Input();
        var expected = ReadCsv("average_drawdown");
        using var avg = new AverageDrawdown(20);
        for (var i = 0; i < input.Length; i++)
        {
            // generator fed the close column as the equity-curve sample.
            AssertClose(avg.Update(input[i][3]), Cell(expected[i][0]), i, "average_drawdown");
        }
    }
}
