"""Tests for upload module."""
import json
import sys

import matplotlib.pyplot as plt  # type: ignore
from . import Upload


def test_mask_rbai() -> None:
    """Test mask to polygon conversion."""
    if sys.platform not in ("linux", "darwin"):
        # Don't run this test for windows, w/o rasterio will fail.
        assert True
        return
    # read mask that was generated by rbai export
    # i.e. rbai polygon -> png mask format
    mask = plt.imread(
        "redbrick/upload/mask_test/88664c8f-c6f8-4d5a-918e-41d8441a4509.png"
    )
    with open(
        "redbrick/upload/mask_test/class_map.json", "r", encoding="utf-8"
    ) as file:
        class_map = json.load(file)

    # convert the mask to rbai polygon
    dp_entry = Upload.mask_to_rbai(mask, class_map, "items123", "name123")

    # read original rbai polygon format
    with open(
        "redbrick/upload/mask_test/redbrick_export_segment.json", "r", encoding="utf-8"
    ) as file:
        datapoints = json.load(file)
    dp_entry_real = datapoints[0]

    # compare the two polygon formats to confirm mask -> polygon is correct
    for label_real in dp_entry_real["labels"]:
        for label in dp_entry["labels"]:
            if label_real["category"] == label["category"]:
                assert (
                    label_real["pixel"]["regions"].sort()
                    == label["pixel"]["regions"].sort()
                )

                if label_real["pixel"]["holes"]:
                    assert (
                        label_real["pixel"]["holes"].sort()
                        == label["pixel"]["holes"].sort()
                    )
