using DiunaBI.Domain.Entities;
using DiunaBI.Infrastructure.Data;
using DiunaBI.Infrastructure.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace DiunaBI.Plugins.Morska.Processors;

public class MorskaT3MultiSourceCopySelectedCodesProcessor : MorskaBaseProcessor
{
    public override string ProcessorType => "T3.MultiSourceCopySelectedCodes";

    private readonly AppDbContext _db;
    private readonly ILogger<MorskaT3MultiSourceCopySelectedCodesProcessor> _logger;

    // Configuration properties loaded from layer records
    private int Year { get; set; }
    private int Month { get; set; }
    private List<Record>? Sources { get; set; }
    private string? Codes { get; set; }
    private List<int>? CodesList { get; set; }

    public MorskaT3MultiSourceCopySelectedCodesProcessor(
        AppDbContext db,
        ILogger<MorskaT3MultiSourceCopySelectedCodesProcessor> logger)
    {
        _db = db;
        _logger = logger;
    }

    public override void Process(Layer processWorker)
    {
        try
        {
            _logger.LogInformation("{ProcessorType}: Starting processing for {ProcessWorkerName} ({ProcessWorkerId})",
                ProcessorType, processWorker.Name, processWorker.Id);

            // Load configuration from layer records
            LoadConfiguration(processWorker);

            // Validate required configuration
            ValidateConfiguration();

            // Perform the actual processing
            PerformProcessing(processWorker);

            _logger.LogInformation("{ProcessorType}: Successfully completed processing for {ProcessWorkerName}",
                ProcessorType, processWorker.Name);
        }
        catch (Exception e)
        {
            _logger.LogError(e, "{ProcessorType}: Failed to process {ProcessWorkerName} ({ProcessWorkerId})",
                ProcessorType, processWorker.Name, processWorker.Id);
            throw;
        }
    }

    private void LoadConfiguration(Layer processWorker)
    {
        if (processWorker.Records == null)
        {
            throw new InvalidOperationException("ProcessWorker has no records");
        }

        // Load year
        var yearStr = GetRecordValue(processWorker.Records, "Year");
        if (string.IsNullOrEmpty(yearStr) || !int.TryParse(yearStr, out var year))
        {
            throw new InvalidOperationException("Year record not found or invalid");
        }
        Year = year;

        // Load month
        var monthStr = GetRecordValue(processWorker.Records, "Month");
        if (string.IsNullOrEmpty(monthStr) || !int.TryParse(monthStr, out var month))
        {
            throw new InvalidOperationException("Month record not found or invalid");
        }
        Month = month;

        // Load sources
        Sources = processWorker.Records.Where(x => x.Code == "Source").ToList();
        if (Sources.Count == 0)
        {
            throw new InvalidOperationException("Source records not found");
        }

        // Load codes
        Codes = GetRecordValue(processWorker.Records, "Codes");
        if (string.IsNullOrEmpty(Codes))
        {
            throw new InvalidOperationException("Codes record not found");
        }

        // Parse codes list
        CodesList = ProcessHelper.ParseCodes(Codes);

        _logger.LogDebug("{ProcessorType}: Configuration loaded - Year: {Year}, Month: {Month}, Sources: {SourceCount}, Codes: {CodeCount}",
            ProcessorType, Year, Month, Sources.Count, CodesList.Count);
    }

    private void ValidateConfiguration()
    {
        var errors = new List<string>();

        if (Year < 2000 || Year > 3000) errors.Add($"Invalid year: {Year}");
        if (Month < 1 || Month > 12) errors.Add($"Invalid month: {Month}");
        if (Sources == null || Sources.Count == 0) errors.Add("No sources configured");
        if (CodesList == null || CodesList.Count == 0) errors.Add("No codes configured");

        if (errors.Any())
        {
            throw new InvalidOperationException($"Configuration validation failed: {string.Join(", ", errors)}");
        }

        _logger.LogDebug("{ProcessorType}: Configuration validation passed", ProcessorType);
    }

    private void PerformProcessing(Layer processWorker)
    {
        _logger.LogDebug("{ProcessorType}: Processing data for Year: {Year}, Month: {Month} with {SourceCount} sources",
            ProcessorType, Year, Month, Sources!.Count);

        // Get or create processed layer
        var processedLayer = GetOrCreateProcessedLayer(processWorker);

        // Get data sources
        var dataSources = GetDataSources();

        // Process records
        var newRecords = ProcessRecords(dataSources);

        // Save results
        SaveProcessedLayer(processedLayer, newRecords);

        _logger.LogInformation("{ProcessorType}: Successfully processed {RecordCount} records for layer {LayerName} ({LayerId})",
            ProcessorType, newRecords.Count, processedLayer.Name, processedLayer.Id);
    }

    private Layer GetOrCreateProcessedLayer(Layer processWorker)
    {
        var processedLayer = _db.Layers
            .Where(x => x.ParentId == processWorker.Id && !x.IsDeleted && !x.IsCancelled)
            .OrderByDescending(x => x.CreatedAt)
            .FirstOrDefault();

        if (processedLayer == null)
        {
            processedLayer = new Layer
            {
                Id = Guid.NewGuid(),
                Type = LayerType.Processed,
                ParentId = processWorker.Id,
                Number = _db.Layers.Count() + 1,
                CreatedById = Guid.Parse("F392209E-123E-4651-A5A4-0B1D6CF9FF9D"),
                ModifiedById = Guid.Parse("F392209E-123E-4651-A5A4-0B1D6CF9FF9D"),
                CreatedAt = DateTime.UtcNow,
                ModifiedAt = DateTime.UtcNow
            };
            processedLayer.Name = $"L{processedLayer.Number}-P-{Year}/{Month:D2}-AB-T3";

            _logger.LogDebug("{ProcessorType}: Created new processed layer {LayerName}",
                ProcessorType, processedLayer.Name);
        }
        else
        {
            processedLayer.ModifiedById = Guid.Parse("F392209E-123E-4651-A5A4-0B1D6CF9FF9D");
            processedLayer.ModifiedAt = DateTime.UtcNow;

            _logger.LogDebug("{ProcessorType}: Using existing processed layer {LayerName}",
                ProcessorType, processedLayer.Name);
        }

        return processedLayer;
    }

    private List<Layer> GetDataSources()
    {
        var dataSources = new List<Layer>();

        foreach (var source in Sources!)
        {
            var dataSource = _db.Layers
                .Where(x => x.Type == LayerType.Processed && 
                           !x.IsDeleted && !x.IsCancelled && 
                           x.Name != null && x.Name.Contains($"{Year}/{Month:D2}-{source.Desc1}-T3"))
                .Include(x => x.Records)
                .AsNoTracking()
                .FirstOrDefault();

            if (dataSource == null)
            {
                _logger.LogWarning("{ProcessorType}: Data source not found for {Year}/{Month:D2}-{Source}-T3",
                    ProcessorType, Year, Month, source.Desc1);
                continue;
            }

            dataSources.Add(dataSource);
            _logger.LogDebug("{ProcessorType}: Found data source {LayerName} with {RecordCount} records",
                ProcessorType, dataSource.Name, dataSource.Records?.Count ?? 0);
        }

        if (dataSources.Count == 0)
        {
            throw new InvalidOperationException($"No data sources found for {Year}/{Month:D2}");
        }

        _logger.LogDebug("{ProcessorType}: Found {DataSourceCount} data sources",
            ProcessorType, dataSources.Count);

        return dataSources;
    }

    private List<Record> ProcessRecords(List<Layer> dataSources)
    {
        var allSourceRecords = dataSources.SelectMany(x => x.Records!).ToList();
        
        var filteredRecords = allSourceRecords
            .Where(x => !string.IsNullOrEmpty(x.Code) && 
                       int.TryParse(x.Code, out var code) && 
                       CodesList!.Contains(code))
            .ToList();

        _logger.LogDebug("{ProcessorType}: Filtered {FilteredCount} records from {TotalCount} total records using {CodeCount} codes",
            ProcessorType, filteredRecords.Count, allSourceRecords.Count, CodesList!.Count);

        var newRecords = filteredRecords.Select(x => CreateCopiedRecord(x)).ToList();

        _logger.LogDebug("{ProcessorType}: Created {NewRecordCount} copied records",
            ProcessorType, newRecords.Count);

        return newRecords;
    }

    private Record CreateCopiedRecord(Record sourceRecord)
    {
        var newRecord = new Record
        {
            Id = Guid.NewGuid(),
            Code = sourceRecord.Code,
            CreatedAt = DateTime.UtcNow,
            ModifiedAt = DateTime.UtcNow
        };

        // Copy all values from positions 1-32
        for (var i = 1; i < 33; i++)
        {
            var value = ProcessHelper.GetValue(sourceRecord, i);
            ProcessHelper.SetValue(newRecord, i, value);
        }

        _logger.LogDebug("{ProcessorType}: Copied record {Code} with values from positions 1-32",
            ProcessorType, newRecord.Code);

        return newRecord;
    }

    private void SaveProcessedLayer(Layer processedLayer, List<Record> newRecords)
    {
        var existsInDb = _db.Layers.Any(x => x.Id == processedLayer.Id);

        if (!existsInDb)
        {
            _db.Layers.Add(processedLayer);
            _logger.LogDebug("{ProcessorType}: Added new processed layer to database", ProcessorType);
        }
        else
        {
            _db.Layers.Update(processedLayer);
            _logger.LogDebug("{ProcessorType}: Updated existing processed layer in database", ProcessorType);
        }

        SaveRecords(processedLayer.Id, newRecords);
        _db.SaveChanges();

        _logger.LogDebug("{ProcessorType}: Saved {RecordCount} records for layer {LayerId}",
            ProcessorType, newRecords.Count, processedLayer.Id);
    }

    private void SaveRecords(Guid layerId, ICollection<Record> records)
    {
        // Remove existing records for this layer
        var toDelete = _db.Records.Where(x => x.LayerId == layerId).ToList();
        if (toDelete.Count > 0)
        {
            _db.Records.RemoveRange(toDelete);
            _logger.LogDebug("{ProcessorType}: Removed {DeletedCount} existing records for layer {LayerId}",
                ProcessorType, toDelete.Count, layerId);
        }

        // Add new records
        foreach (var record in records)
        {
            record.CreatedById = Guid.Parse("F392209E-123E-4651-A5A4-0B1D6CF9FF9D");
            record.CreatedAt = DateTime.UtcNow;
            record.ModifiedById = Guid.Parse("F392209E-123E-4651-A5A4-0B1D6CF9FF9D");
            record.ModifiedAt = DateTime.UtcNow;
            record.LayerId = layerId;
            _db.Records.Add(record);
        }

        _logger.LogDebug("{ProcessorType}: Added {RecordCount} new records for layer {LayerId}",
            ProcessorType, records.Count, layerId);
    }

    private string? GetRecordValue(ICollection<Record> records, string code)
    {
        return records.FirstOrDefault(x => x.Code == code)?.Desc1;
    }
}