using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NT8.Adapters.NinjaTrader;
using NT8.Adapters.Wrappers;
using NT8.Core.Common.Models;
using NT8.Core.Logging;
using NT8.Core.Risk;
using NT8.Core.Sizing;

namespace NT8.Integration.Tests
{
    /// <summary>
    /// Integration tests for end-to-end SDK workflow coverage.
    /// </summary>
    [TestClass]
    public class NT8IntegrationTests
    {
        private StrategyContext CreateTestContext(string symbol, int qty, double equity, double dailyPnl)
        {
            var now = new DateTime(2026, 2, 17, 10, 30, 0, DateTimeKind.Utc);

            var position = new Position(symbol, qty, 4200.0, 0.0, dailyPnl, now);
            var account = new AccountInfo(equity, equity * 2.5, dailyPnl, 0.0, now);
            var session = new MarketSession(now.Date.AddHours(9).AddMinutes(30), now.Date.AddHours(16), true, "RTH");

            return new StrategyContext(symbol, now, position, account, session, new Dictionary<string, object>());
        }

        private BarData CreateTestBar(string symbol)
        {
            return new BarData(
                symbol,
                new DateTime(2026, 2, 17, 10, 30, 0, DateTimeKind.Utc),
                4200.0,
                4210.0,
                4195.0,
                4208.0,
                10000,
                TimeSpan.FromMinutes(5));
        }

        [TestMethod]
        public void CompleteWorkflow_StrategyToExecution_ShouldProcessIntent()
        {
            var wrapper = new SimpleORBNT8Wrapper();
            var symbol = "ES";
            var sessionStart = new DateTime(2026, 2, 17, 9, 30, 0, DateTimeKind.Utc);

            var openingBar1 = new BarData(symbol, sessionStart.AddMinutes(5), 100, 101, 99, 100.5, 1000, TimeSpan.FromMinutes(5));
            var openingBar2 = new BarData(symbol, sessionStart.AddMinutes(10), 100.5, 102, 100, 101.5, 1000, TimeSpan.FromMinutes(5));
            var breakoutBar = new BarData(symbol, sessionStart.AddMinutes(35), 102, 104.5, 101.5, 104.2, 1200, TimeSpan.FromMinutes(5));

            wrapper.ProcessBarUpdate(openingBar1, CreateTestContext(symbol, 0, 100000.0, 0.0));
            wrapper.ProcessBarUpdate(openingBar2, CreateTestContext(symbol, 0, 100000.0, 0.0));
            wrapper.ProcessBarUpdate(breakoutBar, CreateTestContext(symbol, 0, 100000.0, 0.0));

            var records = wrapper.GetAdapterForTesting().GetExecutionHistory();
            Assert.IsNotNull(records);
            Assert.IsTrue(records.Count >= 1);
        }

        [TestMethod]
        public void DataConversion_NT8ToSDK_ShouldPreserveData()
        {
            var time = new DateTime(2026, 2, 17, 10, 0, 0, DateTimeKind.Utc);
            var bar = NT8DataConverter.ConvertBar("ES", time, 4200.0, 4215.0, 4192.0, 4210.0, 15000, 5);

            Assert.AreEqual("ES", bar.Symbol);
            Assert.AreEqual(time, bar.Time);
            Assert.AreEqual(4200.0, bar.Open);
            Assert.AreEqual(4215.0, bar.High);
            Assert.AreEqual(4192.0, bar.Low);
            Assert.AreEqual(4210.0, bar.Close);
            Assert.AreEqual(15000L, bar.Volume);
            Assert.AreEqual(TimeSpan.FromMinutes(5), bar.BarSize);
        }

        [TestMethod]
        public void ExecutionAdapter_OrderLifecycle_ShouldTrackCorrectly()
        {
            var adapter = new NT8ExecutionAdapter();
            var req = new NT8.Core.OMS.OrderRequest();
            req.Symbol = "ES";
            req.Side = NT8.Core.OMS.OrderSide.Buy;
            req.Type = NT8.Core.OMS.OrderType.Market;
            req.Quantity = 2;

            var tracking = adapter.SubmitOrder(req, "TEST_001");
            Assert.AreEqual(NT8.Core.OMS.OrderState.Pending, tracking.CurrentState);

            adapter.ProcessOrderUpdate("NT8_1", "TEST_001", "WORKING", 0, 0.0, 0, null);
            Assert.AreEqual(NT8.Core.OMS.OrderState.Working, adapter.GetOrderStatus("TEST_001").State);

            adapter.ProcessOrderUpdate("NT8_1", "TEST_001", "PARTFILLED", 1, 4200.50, 0, null);
            adapter.ProcessExecution("NT8_1", "EXEC_1", 4200.50, 1, DateTime.UtcNow);
            Assert.AreEqual(NT8.Core.OMS.OrderState.PartiallyFilled, adapter.GetOrderStatus("TEST_001").State);

            adapter.ProcessOrderUpdate("NT8_1", "TEST_001", "FILLED", 2, 4201.00, 0, null);
            adapter.ProcessExecution("NT8_1", "EXEC_2", 4201.00, 1, DateTime.UtcNow);
            Assert.AreEqual(NT8.Core.OMS.OrderState.Filled, adapter.GetOrderStatus("TEST_001").State);
        }

        [TestMethod]
        public void RiskManager_DailyLossLimit_ShouldRejectOverRisk()
        {
            var logger = new BasicLogger("Risk");
            var risk = new BasicRiskManager(logger);

            risk.OnPnLUpdate(-950.0, -950.0);

            var intent = new StrategyIntent(
                "ES",
                OrderSide.Buy,
                OrderType.Market,
                null,
                10,
                20,
                0.9,
                "Risk test",
                new Dictionary<string, object>());

            var context = CreateTestContext("ES", 0, 100000.0, -950.0);
            var cfg = new RiskConfig(1000.0, 200.0, 3, true);

            var decision = risk.ValidateOrder(intent, context, cfg);
            Assert.IsFalse(decision.Allow);
        }

        [TestMethod]
        public void PositionSizer_FixedDollarRisk_ShouldCalculateCorrectly()
        {
            var logger = new BasicLogger("Sizer");
            var sizer = new BasicPositionSizer(logger);

            var intent = new StrategyIntent(
                "ES",
                OrderSide.Buy,
                OrderType.Market,
                null,
                8,
                16,
                0.8,
                "Sizing test",
                new Dictionary<string, object>());

            var context = CreateTestContext("ES", 0, 100000.0, 0.0);
            var cfg = new SizingConfig(SizingMethod.FixedDollarRisk, 1, 10, 100.0, new Dictionary<string, object>());

            var result = sizer.CalculateSize(intent, context, cfg);
            Assert.IsTrue(result.Contracts > 0);
            Assert.IsTrue(result.Contracts <= 10);
            Assert.AreEqual(SizingMethod.FixedDollarRisk, result.Method);
        }

        [TestMethod]
        public void ExecutionAdapter_ConcurrentAccess_ShouldBeThreadSafe()
        {
            var adapter = new NT8ExecutionAdapter();
            var exceptions = new List<Exception>();
            var sync = new object();
            var success = 0;

            var threadList = new List<Thread>();
            for (var t = 0; t < 10; t++)
            {
                var tn = t;
                var thread = new Thread(delegate()
                {
                    try
                    {
                        for (var i = 0; i < 10; i++)
                        {
                            var req = new NT8.Core.OMS.OrderRequest();
                            req.Symbol = "ES";
                            req.Side = NT8.Core.OMS.OrderSide.Buy;
                            req.Type = NT8.Core.OMS.OrderType.Market;
                            req.Quantity = 1;

                            var id = string.Format("TH_{0}_{1}", tn, i);
                            adapter.SubmitOrder(req, id);
                            adapter.ProcessOrderUpdate(id + "_NT8", id, "WORKING", 0, 0.0, 0, null);

                            lock (sync)
                            {
                                success++;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        lock (sync)
                        {
                            exceptions.Add(ex);
                        }
                    }
                });

                threadList.Add(thread);
                thread.Start();
            }

            foreach (var thread in threadList)
            {
                thread.Join();
            }

            Assert.AreEqual(0, exceptions.Count);
            Assert.AreEqual(100, success);
        }

        [TestMethod]
        public void PerformanceTest_OnBarUpdate_ShouldComplete200ms()
        {
            var wrapper = new SimpleORBNT8Wrapper();
            var context = CreateTestContext("ES", 0, 100000.0, 0.0);
            var bar = CreateTestBar("ES");

            for (var i = 0; i < 10; i++)
                wrapper.ProcessBarUpdate(bar, context);

            var iterations = 100;
            var started = DateTime.UtcNow;
            for (var i = 0; i < iterations; i++)
            {
                wrapper.ProcessBarUpdate(bar, context);
            }
            var elapsed = (DateTime.UtcNow - started).TotalMilliseconds / iterations;
            Assert.IsTrue(elapsed < 200.0, string.Format("Average processing time too high: {0:F2} ms", elapsed));
        }

        [TestMethod]
        public void ExecutionAdapter_CancelUnknownOrder_ShouldReturnFalse()
        {
            var adapter = new NT8ExecutionAdapter();
            var result = adapter.CancelOrder("missing");
            Assert.IsFalse(result);
        }

        [TestMethod]
        public void ExecutionAdapter_GetOrderStatus_EmptyId_ShouldReturnNull()
        {
            var adapter = new NT8ExecutionAdapter();
            Assert.IsNull(adapter.GetOrderStatus(""));
        }

        [TestMethod]
        public void DataConverter_ConvertContext_WithCustomData_ShouldCloneDictionary()
        {
            var custom = new Dictionary<string, object>();
            custom.Add("k1", 1);
            custom.Add("k2", "v2");

            var ctx = NT8DataConverter.ConvertContext(
                "ES",
                DateTime.UtcNow,
                new Position("ES", 0, 0, 0, 0, DateTime.UtcNow),
                new AccountInfo(100000.0, 200000.0, 0.0, 0.0, DateTime.UtcNow),
                new MarketSession(DateTime.Today.AddHours(9.5), DateTime.Today.AddHours(16), true, "RTH"),
                custom);

            custom.Add("k3", 3);
            Assert.AreEqual(2, ctx.CustomData.Count);
        }

        [TestMethod]
        public void DataConverter_ConvertSession_OvernightSession_ShouldWork()
        {
            var start = new DateTime(2026, 2, 17, 18, 0, 0, DateTimeKind.Utc);
            var end = new DateTime(2026, 2, 18, 9, 30, 0, DateTimeKind.Utc);
            var session = NT8DataConverter.ConvertSession(start, end, false, "ETH");
            Assert.IsFalse(session.IsRth);
            Assert.AreEqual("ETH", session.SessionName);
        }

        [TestMethod]
        public void DataConverter_ConvertPosition_WithShortQuantity_ShouldPreserveNegative()
        {
            var pos = NT8DataConverter.ConvertPosition("ES", -2, 4200.0, -150.0, 25.0, DateTime.UtcNow);
            Assert.AreEqual(-2, pos.Quantity);
            Assert.AreEqual(-150.0, pos.UnrealizedPnL);
        }

        [TestMethod]
        public void DataConverter_ConvertAccount_WithNegativePnL_ShouldPreserveValue()
        {
            var account = NT8DataConverter.ConvertAccount(100000.0, 180000.0, -1234.5, 5000.0, DateTime.UtcNow);
            Assert.AreEqual(-1234.5, account.DailyPnL);
        }

        [TestMethod]
        public void RiskManager_ValidIntentUnderLimits_ShouldAllow()
        {
            var logger = new BasicLogger("RiskAllow");
            var risk = new BasicRiskManager(logger);
            risk.OnPnLUpdate(0.0, 0.0);

            var intent = new StrategyIntent(
                "MES",
                OrderSide.Buy,
                OrderType.Market,
                null,
                8,
                12,
                0.7,
                "allow",
                new Dictionary<string, object>());

            var decision = risk.ValidateOrder(
                intent,
                CreateTestContext("MES", 0, 50000.0, 0.0),
                new RiskConfig(1000.0, 200.0, 3, true));

            Assert.IsTrue(decision.Allow);
        }

        [TestMethod]
        public void PositionSizer_InvalidIntent_ShouldReturnZeroContracts()
        {
            var logger = new BasicLogger("InvalidIntent");
            var sizer = new BasicPositionSizer(logger);

            var invalid = new StrategyIntent(
                "",
                OrderSide.Flat,
                OrderType.Market,
                null,
                0,
                null,
                -1.0,
                "",
                new Dictionary<string, object>());

            var result = sizer.CalculateSize(
                invalid,
                CreateTestContext("ES", 0, 100000.0, 0.0),
                new SizingConfig(SizingMethod.FixedDollarRisk, 1, 10, 100.0, new Dictionary<string, object>()));

            Assert.AreEqual(0, result.Contracts);
        }
    }
}

