using UnityEngine;

/// <summary>
/// Enhanced diagnostic script specifically for debugging settlement coordinate issues
/// </summary>
public class SettlementCoordinateDiagnostic : MonoBehaviour
{
    [ContextMenu("Debug Settlement Coordinates")]
    public void DebugSettlementCoordinates()
    {
        Debug.Log("=== SETTLEMENT COORDINATE DIAGNOSTIC ===");

        var settlementManager = FindFirstObjectByType<SettlementInteractionManager>();
        var teamMarker = GameObject.Find("TeamMarker");
        var mapMaker = FindFirstObjectByType<MapMaker2>();

        if (settlementManager == null || teamMarker == null || mapMaker == null)
        {
            Debug.LogError("❌ Missing components for coordinate diagnostic");
            return;
        }

        var mapData = mapMaker.GetMapData();
        if (mapData == null)
        {
            Debug.LogError("❌ MapData is null");
            return;
        }

        // Get current team position
        Vector3 worldPos = teamMarker.transform.position;
        Vector2 teamWorldPos = new Vector2(worldPos.x, worldPos.z);
        Debug.Log($"🎯 TeamMarker World Position: {worldPos}");
        Debug.Log($"🎯 TeamMarker 2D Position: {teamWorldPos}");

        // Test coordinate conversion (replicate SettlementInteractionManager logic)
        Debug.Log("\n🔍 COORDINATE CONVERSION TEST:");

        // Get tile size from MapVisualizer
        float tileSize = 1f;
        var mapVisualizer = FindFirstObjectByType<MapVisualizer>();
        if (mapVisualizer != null && mapVisualizer.tileSize > 0)
        {
            tileSize = mapVisualizer.tileSize;
            Debug.Log($"   MapVisualizer tileSize: {tileSize}");
        }
        else
        {
            Debug.Log($"   Using default tileSize: {tileSize}");
        }

        // Convert world to map coordinates (same as SettlementInteractionManager)
        Vector2Int mapPos = new Vector2Int(
            Mathf.RoundToInt(teamWorldPos.x / tileSize),
            Mathf.RoundToInt(teamWorldPos.y / tileSize)
        );
        Debug.Log($"   Converted Map Position: {mapPos}");

        // Check settlements near this position
        Debug.Log("\n🏛️ SETTLEMENT PROXIMITY CHECK:");
        var allSettlements = mapData.GetAllSettlements();
        Debug.Log($"   Total settlements: {allSettlements.Count}");

        int foundNearby = 0;
        float interactionDistance = 2f; // Default from SettlementInteractionManager

        foreach (var settlement in allSettlements)
        {
            float distance = Vector2Int.Distance(mapPos, settlement.position);
            if (distance <= 5f) // Show all within 5 tiles for debugging
            {
                string status = distance <= interactionDistance ? "✅ WITHIN RANGE" : "❌ TOO FAR";
                Debug.Log($"   Settlement '{settlement.name}' at {settlement.position}, distance: {distance:F1} {status}");

                if (distance <= interactionDistance)
                {
                    foundNearby++;
                }
            }
        }

        Debug.Log($"   Settlements within interaction distance ({interactionDistance}): {foundNearby}");

        // Test MapData.GetSettlementAt method
        Debug.Log("\n🔍 MAPDATA.GETSETTLEMENTAT TEST:");
        var foundSettlement = mapData.GetSettlementAt(mapPos, interactionDistance);
        Debug.Log($"   MapData.GetSettlementAt({mapPos}, {interactionDistance}): {(foundSettlement != null ? foundSettlement.name : "NULL")}");

        // Manual verification - check exact position
        Debug.Log("\n🎯 EXACT POSITION CHECK:");
        foreach (var settlement in allSettlements)
        {
            if (settlement.position == mapPos)
            {
                Debug.Log($"   ✅ EXACT MATCH: Settlement '{settlement.name}' at exactly {settlement.position}");
            }
        }
    }
}
