import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from cityHeat import (
    initialize_city,
    apply_diffusion,
    get_avg_temp,
    add_green_infrastructure,
    generate_shadow_mask,
    apply_solar_heating,
    BUILDING_VALUE
)


# ==========================================
# VISUALIZATION & SIMULATION
# ==========================================

def simulate_and_visualize(land_grid, thermal_props, n_steps, include_solar_heating=False, 
                          sun_direction='N', shadow_length=2, solar_intensity=5.0,
                          include_green_infrastructure=False, cooling_points=None):
    """
    Runs the full simulation: initialization, multiple diffusion steps, and plotting.
    """
    # 1. Initialize
    current_temp = initialize_city(land_grid, thermal_props)
    if current_temp is None:
        print("[ERROR] simulate_and_visualize: initialize_city returned None. Check your implementation.")
        return

    history = [("Initial State", [row[:] for row in current_temp])]
    
    if cooling_points is None:
        cooling_points = []
    
    # 2. Run Diffusion Steps
    for i in range(1, n_steps + 1):
        # Apply solar heating if enabled
        if include_solar_heating:
            shadow_mask = generate_shadow_mask(land_grid, sun_direction, shadow_length)
            if shadow_mask is None:
                print(f"[ERROR] simulate_and_visualize: generate_shadow_mask returned None at step {i}.")
                return
            
            current_temp = apply_solar_heating(current_temp, shadow_mask, solar_intensity)
            if current_temp is None:
                print(f"[ERROR] simulate_and_visualize: apply_solar_heating returned None at step {i}.")
                return
        
        current_temp = apply_diffusion(current_temp)
        if current_temp is None:
            print(f"[ERROR] simulate_and_visualize: apply_diffusion returned None at step {i}.")
            return
        
        # Apply green infrastructure if enabled
        if include_green_infrastructure:
            current_temp = add_green_infrastructure(current_temp, cooling_points)
            if current_temp is None:
                print(f"[ERROR] simulate_and_visualize: add_green_infrastructure returned None at step {i}.")
                return
        
        history.append((f"Step {i}", [row[:] for row in current_temp]))

    # 3. Dynamic Plotting
    num_plots = len(history) + 1
    cols = 3 if num_plots > 3 else num_plots
    rows = (num_plots + cols - 1) // cols
    fig, axes = plt.subplots(rows, cols, figsize=(cols * 3, rows * 2.5))
    axes = axes.flatten() if num_plots > 1 else [axes]

    cmap_land = mcolors.ListedColormap(['#333333', '#888888', '#2ecc71', '#3498db'])
    color_map_chars = {'A': 0, 'B': 1, 'G': 2, 'W': 3}
    cmap_temp = plt.get_cmap('jet').copy()
    cmap_temp.set_bad(color='#888888')

    # Plot Land Cover
    numeric_land = [[color_map_chars.get(char, 0) for char in row] for row in land_grid]
    im1 = axes[0].imshow(numeric_land, cmap=cmap_land)
    axes[0].set_title("Land Cover", fontsize=10)
    axes[0].axis('off')
    cbar1 = plt.colorbar(im1, ax=axes[0], fraction=0.046, pad=0.04)
    cbar1.set_ticks([])

    # Plot Temperature History
    for i, (title, grid) in enumerate(history):
        ax = axes[i + 1]
        temp_array = np.array(grid, dtype=float)
        im = ax.imshow(temp_array, cmap=cmap_temp, vmin=20, vmax=35)
        
        avg = get_avg_temp(grid)
        avg_str = f"{avg:.1f}" if avg is not None else "N/A"
        ax.set_title(f"{title} (Avg: {avg_str}°C)", fontsize=10)
        ax.axis('off')
        plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04)

    for j in range(num_plots, len(axes)):
        axes[j].axis('off')

    plt.tight_layout()
    plt.show()


def visualize_city(land_grid, temp_grid):
    """
    A robust visualization function for students to test their initialize_city.
    """
    if temp_grid is None:
        print("[ERROR] visualize_city: The temperature grid you provided is 'None'.")
        print("Did you forget to 'return' the grid in your function?")
        return

    if not isinstance(temp_grid, list) or not isinstance(temp_grid[0], list):
        print("[ERROR] visualize_city: The temperature grid must be a 2D list (list of lists).")
        return

    if len(temp_grid) != len(land_grid) or len(temp_grid[0]) != len(land_grid[0]):
        print(f"[ERROR] visualize_city: Dimension mismatch!")
        print(f"Land grid is {len(land_grid)}x{len(land_grid[0])}, but your "
              f"temp grid is {len(temp_grid)}x{len(temp_grid[0])}.")
        return

    for r_idx, row in enumerate(temp_grid):
        for c_idx, val in enumerate(row):
            if val != BUILDING_VALUE and not isinstance(val, (int, float, np.number)):
                print(f"[ERROR] visualize_city: Invalid data type found at ({r_idx}, {c_idx}).")
                print(f"Value is '{val}' ({type(val)}). Only numbers or {BUILDING_VALUE} are allowed.")
                return

    avg = get_avg_temp(temp_grid)
    avg_str = f"{avg:.1f}" if avg is not None else "N/A"

    color_map_chars = {'A': 0, 'B': 1, 'G': 2, 'W': 3}
    numeric_land = [[color_map_chars.get(char, 0) for char in row] for row in land_grid]
    cmap_land = mcolors.ListedColormap(['#333333', '#888888', '#2ecc71', '#3498db'])
    
    temp_array = np.array(temp_grid, dtype=float)
    cmap_temp = plt.get_cmap('jet').copy() 
    cmap_temp.set_bad(color='#888888') 

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 3.5))

    im1 = ax1.imshow(numeric_land, cmap=cmap_land)
    ax1.set_title("Land Cover Reference", fontsize=10)
    ax1.axis('off')
    cbar1 = plt.colorbar(im1, ax=ax1, fraction=0.046, pad=0.04)
    cbar1.set_ticks([]) 

    im2 = ax2.imshow(temp_array, cmap=cmap_temp, vmin=20, vmax=35)
    ax2.set_title(f"Temperature Map (Avg: {avg_str}°C)", fontsize=10)
    ax2.axis('off')
    plt.colorbar(im2, ax=ax2, label='Temp (°C)', fraction=0.046, pad=0.04)

    plt.tight_layout()
    plt.show()


def visualize_solar_heating(land_grid, temp_grid, sun_direction, shadow_length, solar_intensity=5.0):
    """
    Visualizes the effect of solar heating in one step.
    Handles cases where apply_solar_heating is not yet implemented.
    """
    # --- 1. Robustness Checks for Input ---
    if temp_grid is None:
        print("[ERROR] visualize_solar_heating: The temperature grid you provided is 'None'.")
        return

    if not isinstance(temp_grid, list) or not isinstance(temp_grid[0], list):
        print("[ERROR] visualize_solar_heating: The temperature grid must be a 2D list.")
        return

    if len(temp_grid) != len(land_grid) or len(temp_grid[0]) != len(land_grid[0]):
        print(f"[ERROR] visualize_solar_heating: Dimension mismatch!")
        return

    # --- 2. Shadow Mask Check ---
    shadow_mask = generate_shadow_mask(land_grid, sun_direction, shadow_length)
    if shadow_mask is None:
        print("[ERROR] visualize_solar_heating: 'generate_shadow_mask' returned None.")
        return
    if not isinstance(shadow_mask, (list, np.ndarray)):
        print(f"[ERROR] visualize_solar_heating: 'generate_shadow_mask' returned {type(shadow_mask)} instead of a list.")
        return

    # --- 3. Solar Heating Check (with Partial Implementation Handling) ---
    heated_temp_grid = apply_solar_heating(temp_grid, shadow_mask, solar_intensity)
    heating_implemented = True
    if heated_temp_grid is None:
        print("[WARNING] visualize_solar_heating: 'apply_solar_heating' returned None. Displaying shadow mask only.")
        heating_implemented = False
        # Use original temp as placeholder
        heated_array = np.array(temp_grid, dtype=float)
    elif len(heated_temp_grid) != len(temp_grid):
        print("[ERROR] visualize_solar_heating: The output grid dimensions changed after heating!")
        return
    else:
        heated_array = np.array(heated_temp_grid, dtype=float)

    # --- 4. Setup Arrays and Plotting ---
    temp_array = np.array(temp_grid, dtype=float)
    shadow_array = np.array(shadow_mask, dtype=float)

    cmap_temp = plt.get_cmap('jet').copy()
    cmap_temp.set_bad(color='#888888')
    cmap_shadow = plt.get_cmap('Greys')

    fig, axes = plt.subplots(1, 3, figsize=(12, 3.5))

    # Plot 1: Original Temperature
    im1 = axes[0].imshow(temp_array, cmap=cmap_temp, vmin=20, vmax=35)
    axes[0].set_title("Original Temperature (°C)", fontsize=11)
    axes[0].axis('off')
    plt.colorbar(im1, ax=axes[0], label='Temp (°C)', fraction=0.046, pad=0.04)

    # Plot 2: Shadow Mask (Student can test this independently)
    im2 = axes[1].imshow(shadow_array, cmap=cmap_shadow, vmin=0, vmax=1)
    axes[1].set_title(f"Shadow Mask\n(Sun: {sun_direction}, Length: {shadow_length})", fontsize=11)
    axes[1].axis('off')
    plt.colorbar(im2, ax=axes[1], label='1.0=Sun, 0.0=Shadow', fraction=0.046, pad=0.04)

    # Plot 3: After Solar Heating (or Warning Placeholder)
    im3 = axes[2].imshow(heated_array, cmap=cmap_temp, vmin=20, vmax=35)
    
    if not heating_implemented:
        axes[2].set_title("Heating Not Implemented", fontsize=11, color='red')
        # Add text overlay in the center of the plot
        axes[2].text(0.5, 0.5, "apply_solar_heating\nnot implemented yet!", 
                     color='white', fontweight='bold', fontsize=9,
                     ha='center', va='center', transform=axes[2].transAxes,
                     bbox=dict(facecolor='red', alpha=0.5, edgecolor='none'))
    else:
        axes[2].set_title(f"After Solar Heating\n(+{solar_intensity}°C)", fontsize=11)
        
    axes[2].axis('off')
    plt.colorbar(im3, ax=axes[2], label='Temp (°C)', fraction=0.046, pad=0.04)

    plt.tight_layout()
    plt.show()


def visualize_green_infrastructure(land_grid, temp_grid, cooling_points):
    """
    Visualizes the effect of applying green infrastructure in one step.
    """
    if temp_grid is None:
        print("[ERROR] visualize_green_infrastructure: The temperature grid you provided is 'None'.")
        return

    if not isinstance(temp_grid, list) or not isinstance(temp_grid[0], list):
        print("[ERROR] visualize_green_infrastructure: The temperature grid must be a 2D list.")
        return

    if len(temp_grid) != len(land_grid) or len(temp_grid[0]) != len(land_grid[0]):
        print(f"[ERROR] visualize_green_infrastructure: Dimension mismatch!")
        return

    cooled_temp_grid = add_green_infrastructure(temp_grid, cooling_points)
    if cooled_temp_grid is None:
        print("[ERROR] visualize_green_infrastructure: 'add_green_infrastructure' returned None.")
        return
    
    temp_array = np.array(temp_grid, dtype=float)
    cooled_array = np.array(cooled_temp_grid, dtype=float)

    cooling_points_grid = np.zeros((len(temp_grid), len(temp_grid[0])))
    for r, c, strength in cooling_points:
        if 0 <= r < len(temp_grid) and 0 <= c < len(temp_grid[0]):
            cooling_points_grid[r][c] += strength

    cmap_temp = plt.get_cmap('jet').copy()
    cmap_temp.set_bad(color='#888888')
    cmap_points = plt.get_cmap('Greens')

    fig, axes = plt.subplots(1, 3, figsize=(12, 3))

    im1 = axes[0].imshow(temp_array, cmap=cmap_temp, vmin=20, vmax=35)
    axes[0].set_title("Original Temperature (°C)", fontsize=11)
    axes[0].axis('off')
    plt.colorbar(im1, ax=axes[0], label='Temp (°C)', fraction=0.046, pad=0.04)

    max_s = max([s for r, c, s in cooling_points], default=1)
    im2 = axes[1].imshow(cooling_points_grid, cmap=cmap_points, vmin=0, vmax=max_s)
    axes[1].set_title(f"Cooling Points\n({len(cooling_points)} trees planted)", fontsize=11)
    axes[1].axis('off')
    plt.colorbar(im2, ax=axes[1], label='Cooling Strength', fraction=0.046, pad=0.04)

    im3 = axes[2].imshow(cooled_array, cmap=cmap_temp, vmin=20, vmax=35)
    axes[2].set_title("After Green Infrastructure", fontsize=11)
    axes[2].axis('off')
    plt.colorbar(im3, ax=axes[2], label='Temp (°C)', fraction=0.046, pad=0.04)

    plt.tight_layout()
    plt.show()

# ==========================================
# MAIN EXECUTION
# ==========================================

if __name__ == "__main__":
    example_city = [['G','G','G','G','G', 'A', 'A', 'G', 'B', 'B'],
                    ['G','G','G','G','G', 'A', 'A', 'G', 'B', 'B'],
                    ['G','W','W','G','G', 'A', 'A', 'A', 'A', 'A'],
                    ['G','W','W','G','A', 'A', 'A', 'A', 'B', 'B'],
                    ['G','G','G','G','A', 'B', 'B', 'A', 'B', 'B'],
                    ['A','A','A','A','A', 'B', 'B', 'A', 'A', 'A'],
                    ['A','A','A','A','A', 'A', 'A', 'A', 'A', 'A'],
                    ['G','G','G','G','G', 'A', 'A', 'G', 'G', 'G'],
                    ['B','B','B','B','G', 'A', 'A', 'B', 'B', 'B'],
                    ['B','B','B','B','G', 'A', 'A', 'B', 'B', 'B']]

    GROUND_PROPERTIES = {'G': 25.0, 'A': 30.0, 'W': 20.0, 'B': BUILDING_VALUE}


    print("Visualizing initial heat distribution...")
    init_temp = initialize_city(example_city, GROUND_PROPERTIES)
    visualize_city(example_city, init_temp)

    print("\nRunning simulation...")
    simulate_and_visualize(example_city, GROUND_PROPERTIES, n_steps=4)

    cooling_points = [(1, 1, 2.0), (4, 3, 3.0), (7, 7, 1.0), (7, 1, 1.0), (1, 7, 2.0)]
    print("\nVisualizing green infrastructure effect...")
    visualize_green_infrastructure(example_city, init_temp, cooling_points)

    print("\nRunning simulation with green infrastructure...")
    simulate_and_visualize(example_city, GROUND_PROPERTIES, n_steps=4,
                        include_green_infrastructure=True, cooling_points=cooling_points)
    
    print("\nVisualizing solar heating effect...")
    visualize_solar_heating(example_city, init_temp, sun_direction='E', shadow_length=2, solar_intensity=0.5)

    print("\nRunning simulation with solar heating...")
    simulate_and_visualize(example_city, GROUND_PROPERTIES, n_steps=4, 
                        include_solar_heating=True, sun_direction='E', 
                        shadow_length=2, solar_intensity=1.0)

    print("\nRunning simulation with solar heating and green infrastructure...")
    cooling_points = [(1, 1, 2.0), (4, 3, 3.0), (7, 7, 1.0), (7, 1, 1.0), (1, 7, 2.0)]
    simulate_and_visualize(example_city, GROUND_PROPERTIES, n_steps=4,
                        include_solar_heating=True, sun_direction='E', shadow_length=2, solar_intensity=0.5,
                        include_green_infrastructure=True, cooling_points=cooling_points)
