using System;
using System.Collections.Generic;
using System.Linq;
using Decal.Adapter;
using Decal.Filters;
using Newtonsoft.Json;

namespace MosswartMassacre
{
    /// <summary>
    /// Reads dungeon cell geometry from the game's dat files via DECAL FileService.
    /// Detects whether the player is in a dungeon and extracts floor plan data
    /// for streaming to the backend.
    ///
    /// Binary parsing based on UtilityBelt's Dungeon.cs / DungeonCell.cs / IsDungeon.cs.
    /// Must be called from the UI thread (FileService is COM).
    /// </summary>
    public class DungeonMapReader
    {
        private readonly IPluginLogger _logger;
        private readonly Dictionary<uint, bool> _isDungeonCache = new Dictionary<uint, bool>();
        private readonly Dictionary<uint, object> _mapCache = new Dictionary<uint, object>();
        private FileService _fileService;

        public DungeonMapReader(IPluginLogger logger)
        {
            _logger = logger;
        }

        private FileService GetFileService()
        {
            if (_fileService == null)
                _fileService = CoreManager.Current.Filter<FileService>();
            return _fileService;
        }

        /// <summary>
        /// Check if the given landcell is inside a dungeon.
        /// Uses indoor cell bit check + cell file byte 4 flag.
        /// </summary>
        public bool IsDungeon(uint landcell)
        {
            // Indoor cells have cell index >= 0x0100
            if ((landcell & 0x0000FFFF) < 0x0100)
                return false;

            uint landblock = landcell & 0xFFFF0000;

            if (_isDungeonCache.TryGetValue(landblock, out bool cached))
                return cached;

            try
            {
                var fs = GetFileService();
                byte[] cellFile = fs.GetCellFile((int)landcell);

                bool isDungeon;
                if (cellFile == null || cellFile.Length < 5)
                {
                    isDungeon = true; // Assume dungeon if can't read
                }
                else
                {
                    // Byte 4 bit 0: 0 = dungeon, 1 = surface dwelling
                    isDungeon = (cellFile[4] & 0x01) == 0;
                }

                _isDungeonCache[landblock] = isDungeon;
                return isDungeon;
            }
            catch (Exception ex)
            {
                _logger?.Log($"[DungeonMap] IsDungeon check failed: {ex.Message}");
                _isDungeonCache[landblock] = false;
                return false;
            }
        }

        /// <summary>
        /// Read all dungeon cells for the given landcell's landblock.
        /// Returns a serializable payload or null if not a dungeon / already cached.
        /// </summary>
        public object ReadDungeonMap(uint landcell, string characterName)
        {
            uint landblock = landcell & 0xFFFF0000;

            // Already read this dungeon
            if (_mapCache.ContainsKey(landblock))
                return null;

            if (!IsDungeon(landcell))
                return null;

            try
            {
                var fs = GetFileService();

                // Read master dungeon file
                byte[] masterFile = fs.GetCellFile((int)(65534 + landblock));
                if (masterFile == null || masterFile.Length < 8)
                {
                    _logger?.Log($"[DungeonMap] No master file for landblock 0x{landblock:X8}");
                    _mapCache[landblock] = new object(); // Mark as attempted
                    return null;
                }

                int cellCount = BitConverter.ToInt32(masterFile, 4);
                _logger?.Log($"[DungeonMap] Reading {cellCount} cells for landblock 0x{landblock:X8}");

                var allCells = new List<CellData>();
                int minX = int.MaxValue, maxX = int.MinValue;
                int minY = int.MaxValue, maxY = int.MinValue;

                for (int i = 0; i < cellCount; i++)
                {
                    try
                    {
                        int cellId = (int)(i + landblock + 256);
                        byte[] cellFile = fs.GetCellFile(cellId);
                        if (cellFile == null || cellFile.Length < 20)
                            continue;

                        int baseOffset = 16 + (int)cellFile[12] * 2;
                        if (baseOffset + 20 > cellFile.Length)
                            continue;

                        ushort envId = BitConverter.ToUInt16(cellFile, baseOffset);
                        int x = (int)Math.Round(BitConverter.ToSingle(cellFile, baseOffset + 4));
                        int y = (int)Math.Round(BitConverter.ToSingle(cellFile, baseOffset + 8));
                        int z = (int)Math.Round(BitConverter.ToSingle(cellFile, baseOffset + 12));
                        float rotation = BitConverter.ToSingle(cellFile, baseOffset + 16);

                        // Validation: X must be divisible by 10
                        if (x % 10 != 0) continue;

                        allCells.Add(new CellData
                        {
                            env_id = envId,
                            x = x,
                            y = y,
                            z = z,
                            rotation = rotation
                        });

                        if (x < minX) minX = x;
                        if (x > maxX) maxX = x;
                        if (y < minY) minY = y;
                        if (y > maxY) maxY = y;
                    }
                    catch
                    {
                        // Skip individual cell failures
                    }
                }

                if (allCells.Count == 0)
                {
                    _mapCache[landblock] = new object();
                    return null;
                }

                // Group by Z-level
                var zLevels = allCells
                    .GroupBy(c => (int)(Math.Floor((c.z + 3.0) / 6.0) * 6.0))
                    .Select(g => new { z = g.Key, cells = g.ToList() })
                    .OrderBy(g => g.z)
                    .ToList();

                var payload = new
                {
                    type = "dungeon_map",
                    character_name = characterName,
                    landblock = $"0x{landblock:X8}",
                    bounds = new { min_x = minX, max_x = maxX, min_y = minY, max_y = maxY },
                    z_levels = zLevels
                };

                _mapCache[landblock] = payload;
                _logger?.Log($"[DungeonMap] Read {allCells.Count} cells, {zLevels.Count} Z-levels for 0x{landblock:X8}");

                return payload;
            }
            catch (Exception ex)
            {
                _logger?.Log($"[DungeonMap] ReadDungeonMap failed: {ex.Message}");
                _mapCache[landblock] = new object();
                return null;
            }
        }

        private class CellData
        {
            public ushort env_id;
            public int x, y, z;
            public float rotation;
        }
    }
}
