using System;
using System.IO;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;

namespace cAlgo
{
    [Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class HmaClusterDisplay : Indicator
    {
        #region Parameters

        [Parameter("Config File Path", DefaultValue = @"\\COFFEE\cTrader\HmaCluster.txt")]
        public string ConfigFilePath { get; set; }

        #endregion

        #region Outputs

        // SMA with Length SmaBias, Col=#FF01FF01, thickness=2
        [Output("SMA Bias", LineColor = "#FF01FF01", Thickness = 2)]
        public IndicatorDataSeries SmaBiasOutput { get; set; }

        // HMA with Length HmaBias, Col=#FFFF6666, thickness=2
        [Output("HMA Bias", LineColor = "#FFFF6666", Thickness = 2)]
        public IndicatorDataSeries HmaBiasOutput { get; set; }

        // HMA with Length HmaCluster, Col=White, thickness=2
        [Output("HMA Cluster", LineColor = "White", Thickness = 2)]
        public IndicatorDataSeries HmaClusterOutput { get; set; }

        #endregion

        #region Variables

        private SimpleMovingAverage _smaBiasIndicator;
        private HullMovingAverage _hmaBiasIndicator;
        private HullMovingAverage _hmaClusterIndicator;

        // Default values from prompt header
        private int _smaBiasLength = 200;
        private int _hmaBiasLength = 250;
        private int _hmaClusterLength = 25;

        #endregion

        protected override void Initialize()
        {
            LoadConfiguration();

            // Initialize indicators with loaded or default values
            _smaBiasIndicator = Indicators.SimpleMovingAverage(Bars.ClosePrices, _smaBiasLength);
            _hmaBiasIndicator = Indicators.HullMovingAverage(Bars.ClosePrices, _hmaBiasLength);
            _hmaClusterIndicator = Indicators.HullMovingAverage(Bars.ClosePrices, _hmaClusterLength);

            Print($"Initialized: {_smaBiasLength} SMA | {_hmaBiasLength} HMA Bias | {_hmaClusterLength} HMA Cluster");
        }

        public override void Calculate(int index)
        {
            if (_smaBiasIndicator != null)
                SmaBiasOutput[index] = _smaBiasIndicator.Result[index];
            
            if (_hmaBiasIndicator != null)
                HmaBiasOutput[index] = _hmaBiasIndicator.Result[index];
            
            if (_hmaClusterIndicator != null)
                HmaClusterOutput[index] = _hmaClusterIndicator.Result[index];
        }

        private void LoadConfiguration()
        {
            if (!File.Exists(ConfigFilePath))
            {
                Print($"Config file not found at {ConfigFilePath}. Using defaults.");
                return;
            }

            try
            {
                var lines = File.ReadAllLines(ConfigFilePath);
                var currentSymbol = SymbolName;
                // cTrader ShortName returns "m5", "h1", etc. which matches your file format
                var currentTimeframe = TimeFrame.ShortName; 

                foreach (var line in lines)
                {
                    var trimmedLine = line.Trim();
                    
                    // Skip comments and empty lines
                    if (string.IsNullOrWhiteSpace(trimmedLine) || trimmedLine.StartsWith("#"))
                        continue;

                    // Split by whitespace
                    var columns = trimmedLine.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);

                    // Ensure we have enough columns (need at least up to index 6)
                    if (columns.Length < 7) 
                        continue;

                    var cfgSymbol = columns[0];
                    var cfgTimeframe = columns[1];

                    // Check for match (case-insensitive)
                    if (string.Equals(cfgSymbol, currentSymbol, StringComparison.OrdinalIgnoreCase) &&
                        string.Equals(cfgTimeframe, currentTimeframe, StringComparison.OrdinalIgnoreCase))
                    {
                        // Parse values
                        // Col 4: SmaBias
                        // Col 5: HmaBias
                        // Col 6: HmaCluster
                        if (int.TryParse(columns[4], out int sBias) &&
                            int.TryParse(columns[5], out int hBias) &&
                            int.TryParse(columns[6], out int hCluster))
                        {
                            _smaBiasLength = sBias;
                            _hmaBiasLength = hBias;
                            _hmaClusterLength = hCluster;
                            Print($"Configuration found for {currentSymbol} {currentTimeframe}");
                            return; // Stop searching after match
                        }
                    }
                }
                
                Print($"No specific config found for {currentSymbol} {currentTimeframe}. Using defaults.");
            }
            catch (Exception ex)
            {
                Print($"Error reading config file: {ex.Message}. Using defaults.");
            }
        }
    }
}