
from .series import SeriesIndicator
from .utils import (
    group_by_year,
    populate_periods,
)


class CashBalance(SeriesIndicator):
    """
    Cash balance at the end of the financial year.
    """

    name = "cash_balance"
    result_type = "R"
    noun = "cash balance"
    has_comparisons = True
    reference = "solgf"
    formula = {
        "text": "= Cash available at year end",
        "actual": [
            "=", 
            {
                "cube": "cflow",
                "item_codes": ["4200"],
                "amount_type": "AUDA",
            }
        ],
    }

    @classmethod
    def determine_rating(cls, result):
        if result > 0:
            return "good"
        elif result <= 0:
            return "bad"
        else:
            return None

    @classmethod
    def generate_data(cls, year, values):
        data = {
            "date": year,
        }
        if values:
            cash_at_year_end = values["cash_at_year_end"]
            data.update({
                "result": cash_at_year_end,
                "rating": cls.determine_rating(cash_at_year_end),
                "cube_version": values["cube_version"],
            })
        else:
            data.update({
                "result": None,
                "rating": "bad",
                "cube_version": None,
            })
        return data

    @classmethod
    def get_values(cls, years, results):
        periods = {}
        # Populate periods with v1 data
        populate_periods(
            periods,
            group_by_year(results["cash_flow_v1"]),
            ("cash_at_year_end","v1"),
        )
        # Populate periods with v2 data
        populate_periods(
            periods,
            group_by_year(results["cash_flow_v2"]),
            ("cash_at_year_end","v2"),
        )
        # Generate data for the requested years
        return list(
            map(
                lambda year: cls.generate_data(year, periods.get(year)),
                years,
            )
        )


@@ -1,13 +1,12 @@
-%0A
 from .series
@@ -91,16 +91,51 @@
 eriods,%0A
+    filter_for_all_keys_versioned,%0A
 )%0A%0A%0Aclas
@@ -1836,32 +1836,276 @@
 v2%22),%0A        )%0A
+        # Filter out periods that don't have all the required data%0A        periods = filter_for_all_keys_versioned(periods, %5B%0A            %22cash_at_year_end%22,%0A        %5D)%0A        # Convert periods into dictionary%0A        periods = dict(periods)%0A%0A
         # Genera

Fix period dictionery after adding cube version