import copy
import os
import pprint
from cityHeat import (
    initialize_city,
    get_valid_neighbors,
    apply_diffusion,
    get_avg_temp,
    add_green_infrastructure,
    generate_shadow_mask,
    apply_solar_heating,
    BUILDING_VALUE
)
# === Helper functions for test system ===

def green(s): return f"\033[92m{s}\033[0m"
def red(s): return f"\033[91m{s}\033[0m"

def to_sorted_list(value):
    """Helper to compare neighbor lists where order doesn't matter."""
    if isinstance(value, list):
        return sorted(value)
    return value

# === Core test harness ===

def test(function, arguments, ground_truth, test_name, out_transform=None):
    try:
        # Create a deep copy of arguments to ensure the test doesn't fail 
        # because of mutations from previous tests
        args_copy = copy.deepcopy(arguments)
        output = function(*args_copy)
        
        if out_transform is not None:
            output = out_transform(output)
            ground_truth = out_transform(ground_truth)
            
        if output == ground_truth:
            print(f"{green('Test passed:')} {function.__name__} - {test_name}")
        else:
            print(f"{red('Test failed:')} {function.__name__} - {test_name}")
            print(f"=== Arguments: ===")
            pprint.pprint(arguments, width=160)
            print(f"=== Expected: ===")
            pprint.pprint(ground_truth)
            print(f"=== Received: ===")
            pprint.pprint(output)

    except Exception as e:
        print(f"{red('Test failed:')} {function.__name__}")
        print(f"Unhandled Exception: {repr(e)}\n")


# === CITY HEAT TESTS ===

def test_initialize_city():
    ground_props = {'G': 25.0, 'A': 30.0, 'W': 20.0, 'B': BUILDING_VALUE}
    example_city = [
        ['A', 'G', 'G'],
        ['A', 'B', 'G'],
        ['A', 'W', 'W']
    ]
    expected = [
        [30.0, 25.0, 25.0],
        [30.0, BUILDING_VALUE, 25.0],
        [30.0, 20.0, 20.0]
    ]
    test(initialize_city, (example_city, ground_props), expected, "PDF Example")

def test_get_avg_temp():
    temp_grid = [
        [30.0, 25.0, 25.0],
        [30.0, BUILDING_VALUE, 25.0],
        [30.0, 20.0, 20.0]
    ]
    # (30+25+25+30+25+30+20+20) / 8 = 25.625
    expected = 25.625
    test(get_avg_temp, (temp_grid,), expected, "PDF Example")

def test_get_valid_neighbors():
    temp_grid = [
        [30.0, 25.0, 25.0],
        [30.0, BUILDING_VALUE, 25.0],
        [30.0, 20.0, 20.0]
    ]
    # Row 2, Col 1 is the '20.0' at the bottom center
    expected = [30.0, 25.0, 30.0, 20.0]
    test(get_valid_neighbors, (temp_grid, 2, 1), expected,"PDF Example", out_transform=to_sorted_list)

def test_apply_diffusion():
    grid = [
        [30.0, 25.0, 25.0],
        [30.0, BUILDING_VALUE, 25.0],
        [30.0, 20.0, 20.0]
    ]
    expected = [
        [28.75, 26.25, 25.0], 
        [28.125, BUILDING_VALUE, 23.75], 
        [27.5, 23.125, 21.25]
    ]
    test(apply_diffusion, (grid,), expected,"PDF Example")

def test_add_green_infrastructure():
    grid = [
        [30.0, 25.0, 25.0],
        [30.0, BUILDING_VALUE, 25.0],
        [30.0, 20.0, 20.0]
    ]
    points = [(1, 0, 7.0), (1, 1, 1.0), (2, 1, 2.5)]
    expected = [
        [30.0, 25.0, 25.0], 
        [23.0, BUILDING_VALUE, 25.0], 
        [30.0, 17.5, 20.0]
    ]
    test(add_green_infrastructure, (grid, points), expected, "PDF Example")

def test_generate_shadow_mask():
    example_city = [
        ['A', 'G', 'G', 'G', 'G'],
        ['A', 'B', 'G', 'G', 'G'],
        ['A', 'W', 'W', 'W', 'W']
    ]
    
    # Test Short Shadow
    expected_short = [
        [1.0, 1.0, 1.0, 1.0, 1.0],
        [1.0, 0.0, 0.0, 1.0, 1.0],
        [1.0, 1.0, 1.0, 1.0, 1.0]
    ]
    test(generate_shadow_mask, (example_city, 'W', 1), expected_short, "PDF Example - Short Shadow")

    # Test Long Shadow
    expected_long = [
        [1.0, 1.0, 1.0, 1.0, 1.0],
        [1.0, 0.0, 0.0, 0.0, 0.0],
        [1.0, 1.0, 1.0, 1.0, 1.0]
    ]
    test(generate_shadow_mask, (example_city, 'W', 5), expected_long, "PDF Example - Long Shadow")

def test_apply_solar_heating():
    grid = [
        [30.0, 25.0, 25.0, 25.0, 25.0],
        [30.0, BUILDING_VALUE, 25.0, 25.0, 25.0],
        [30.0, 20.0, 20.0, 20.0, 20.0]
    ]
    mask_short = [
        [1.0, 1.0, 1.0, 1.0, 1.0],
        [1.0, 0.0, 0.0, 1.0, 1.0],
        [1.0, 1.0, 1.0, 1.0, 1.0]
    ]
    solar_intensity = 2.0
    expected = [
        [32.0, 27.0, 27.0, 27.0, 27.0], 
        [32.0, BUILDING_VALUE, 25.0, 27.0, 27.0], 
        [32.0, 22.0, 22.0, 22.0, 22.0]
    ]
    test(apply_solar_heating, (grid, mask_short, solar_intensity), expected, "PDF Example - Short Shadow")

def main():
    if os.name == 'nt':
        os.system('color')

    print(f"--- Running CityHeat Simulation Tests ---")
    test_initialize_city()
    test_get_avg_temp()
    test_get_valid_neighbors()
    test_apply_diffusion()
    test_add_green_infrastructure()
    test_generate_shadow_mask()
    test_apply_solar_heating()

if __name__ == '__main__':
    main()