# Problem Description:
- The problem involves a grid containing rectangles that may overlap. Each rectangle has an associated priority. Higher-priority rectangles take precedence over lower-priority rectangles, and the overlapping regions are "trimmed" such that only the highest-priority rectangle occupies the overlapping cells. Given the coordinates of multiple rectangles and their respective priorities, the task is to compute the trimmed area of a specific rectangle after resolving overlaps based on priority.

# Visual Facts:
1. Rectangles and IDs: Rectangles are represented as contiguous rectangular regions in the grid. Each rectangle is associated with an ID (e.g., 1, 2, 3, 4).
2. Priority Order: Each rectangle has a priority level, and a higher id has a higher priority (e.g., 4 > 3 > 2 > 1). Higher-priority rectangles take precedence and "trim" lower-priority rectangles in overlapping regions.
3. Examples in the Image:
- Example 1:
    Priority: 2 > 1
    Rectangle 1 occupies cells (0,0) to (3,2).
    Rectangle 2 occupies cells (2,0) to (5,2).
    Trimming results in Rectangle 2 maintaining its original area, while Rectangle 1 is trimmed to exclude overlapping cells with Rectangle 2.
- Example 2:
    Priority: 3 > 2 > 1.
    Rectangle 1 occupies cells (0,0) to (3,3).
    Rectangle 2 occupies cells (2,0) to (5,2).
    Rectangle 3 occupies cells (3,1) to (5,3).
    Trimming resolves overlaps, and each rectangle retains only the non-overlapping cells.
- Example 3:
    Priority: 4 > 3 > 2 > 1.
    Four rectangles are shown, with overlapping areas resolved based on priority.
    Higher-priority rectangles trim overlapping areas from lower-priority ones.

5. Output Goal: The goal is to calculate the trimmed area of a specific rectangle (based on the given rectangle_id).

# Visual Patterns:
- Priority
    Rectangle with higher id has a higher priority.
- Priority Resolves Overlaps:
    By keeping the integrity of higher priority rectangle(which means higher id) step by step, trim the overlap area.(e.g., starting from the top priority rectangle, keep its integrity and trim any other overlap area from lower id rectangle and repeat this operation until no overlap area exists.)
- Trimming Mechanism:
    The area of a rectangle is reduced if its cells overlap with higher-priority rectangles. The trimmed cells are removed entirely from the lower-priority rectangle's area.
- Rectangles Defined by Coordinates:
    Each rectangle is defined by its bottom-left and top-right coordinates in the grid.
    These coordinates determine the rectangular area before trimming.
- Calculation of Trimmed Area:
    The trimmed area of a rectangle is the count of grid cells it occupies after resolving overlaps.

# Solution
from typing import Dict, List, Tuple

def solution(rectangles: Dict[int, List[Tuple[int, int]]], rectangle_id: int) -> int:    
    """
    Calculate the trimmed area of a specified rectangle within a grid.

    Args:
        rectangles: A dictionary mapping rectangle IDs (int) to their corner coordinates.
                   Each value is a list containing two (column, row) tuples representing 
                   the bottom-left and top-right corners respectively.
                   Example: {1: [(0, 0), (2, 2)], 2: [(2, 0), (4, 2)]}
        rectangle_id: The ID of the target rectangle to calculate the trimmed area for.  

    Returns:
        The trimmed area of the specified rectangle.
    """
    # Sort rectangles by their ID (higher ID = higher priority)
    sorted_rectangles = sorted(rectangles.items(), key=lambda x: -x[0])

    # Initialize a 3x7 grid to track coverage
    grid = [[0] * 7 for _ in range(3)]

    # Fill the grid based on rectangle priority
    for rect_id, coords in sorted_rectangles:
        bottom_left, top_right = coords
        x1, y1 = bottom_left
        x2, y2 = top_right
        for x in range(x1, x2):
            for y in range(y1, y2):
                # Only fill the cell if it hasn't been covered by a higher-priority rectangle
                if grid[y][x] == 0:
                    grid[y][x] = rect_id

    # Calculate the trimmed area for the given rectangle_id
    trimmed_area = sum(1 for y in range(3) for x in range(7) if grid[y][x] == rectangle_id)

    return trimmed_area

# Test Script
def test():
    test_cases = [
        ({1: [(0, 1), (3, 3)], 2: [(0, 0), (4, 2)], 3: [(3, 1), (5, 3)], 4: [(4, 0), (7, 2)]}, 1, 3),
        ({1: [(0, 1), (3, 3)], 2: [(0, 0), (4, 2)], 3: [(3, 1), (5, 3)], 4: [(4, 0), (7, 2)]}, 2, 7),
        ({1: [(0, 1), (3, 3)], 2: [(0, 0), (4, 2)], 3: [(3, 1), (5, 3)], 4: [(4, 0), (7, 2)]}, 3, 3),
        ({1: [(0, 1), (3, 3)], 2: [(0, 0), (4, 2)], 3: [(3, 1), (5, 3)], 4: [(4, 0), (7, 2)]}, 4, 6),
        ({1: [(0, 0), (3, 2)], 2: [(2, 0), (5, 2)]}, 1, 4),
        ({1: [(0, 0), (3, 2)], 2: [(2, 0), (5, 2)]}, 2, 6),
        ({1: [(0, 0), (3, 3)], 2: [(2, 0), (5, 2)], 3: [(3, 1), (5, 3)]}, 1, 7),
        ({1: [(0, 0), (3, 3)], 2: [(2, 0), (5, 2)], 3: [(3, 1), (5, 3)]}, 2, 4),
        ({1: [(0, 0), (3, 3)], 2: [(2, 0), (5, 2)], 3: [(3, 1), (5, 3)]}, 3, 4),
        ({1: [(0, 0), (3, 3)], 2: [(3, 0), (5, 2)], 3: [(5, 1), (7, 3)]}, 3, 4)
    ]

    for i, (rectangles, rectangle_id, expected_output) in enumerate(test_cases):
        try:
            output = solution(rectangles, rectangle_id)
        except Exception as e:
            error_message = (
                f"An exception occurred while running the test case:\n"
                f"`rectangles`: {rectangles}\n"
                f"`rectangle_id`: {rectangle_id}\n\n"
                f"Exception: '{str(e)}'"
            )
            assert False, error_message

        if output != expected_output:
            error_message = (
                f"The following Test Case failed:\n"
                f"`rectangles`: {rectangles}\n"
                f"`rectangle_id`: {rectangle_id}\n\n"
                f"Actual Output: {output}\n"
                f"Expected Output: {expected_output}"
            )
            assert False, error_message

test()