"""Accounting and independent-data checks for the Australia-only reconstruction."""

import json
from pathlib import Path
import tempfile
import unittest

import numpy as np

from income_demographics import build_model, load_data, rake


class DemographicsTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.model = build_model()
        cls.report = cls.model.report()

    def test_every_household_balances(self):
        m = self.model
        np.testing.assert_allclose(m.private + m.benefits - m.tax, m.disposable, atol=1e-8)
        self.assertTrue(np.all(m.weights > 0))
        self.assertTrue(np.all(m.benefits >= 0))
        self.assertTrue(np.all(m.tax >= 0))
        self.assertTrue(np.all(m.tax <= .5 * np.maximum(0, m.gross)))

    def test_independently_published_all_household_totals(self):
        # Not the sum of the profile controls used to fit: ABS publishes this
        # all-household row separately, with its own perturbation and rounding.
        for check in self.report["published_aggregate_checks"].values():
            self.assertLess(abs(check["difference_percent"]), 1)
        self.assertLess(abs(self.report["totals"]["households"] / 9_732_400 - 1), .001)

    def test_held_out_gini_and_gross_deciles(self):
        checks = self.report["distribution_checks"]
        self.assertLess(abs(checks["gross_gini"]["model"] - .436), .015)
        for d in checks["gross_deciles"]:
            if d["percentile"] in (10, 30, 50, 70, 90):
                self.assertLess(abs(d["model"] / d["published"] - 1), .06)

    def test_held_out_disposable_medians_by_family(self):
        for p in self.report["profiles"]:
            self.assertLess(abs(p["median_disposable"] / p["published_median_disposable"] - 1), .06,
                            p["id"])

    def test_income_bands_partition_population_and_money(self):
        m = self.model
        cuts = [-np.inf, 0, 20_000, 50_000, 100_000, 200_000, np.inf]
        summaries = [m.summary(lower=lo, upper=hi) for lo, hi in zip(cuts, cuts[1:])]
        for key, value in m.summary().items():
            self.assertAlmostEqual(sum(row[key] for row in summaries) / value, 1, places=10)
        self.assertGreater(m.zero_private_income(), 0)
        self.assertGreater(m.summary(upper=0)["households"], 0)

    def test_family_groups_are_mutually_exclusive_and_exhaustive(self):
        m = self.model
        families = {p["family"] for p in m.data["profiles"]}
        self.assertAlmostEqual(sum(m.summary(f)["households"] for f in families),
                               m.summary()["households"], places=5)
        with self.assertRaises(ValueError):
            m.summary("unknown")
        with self.assertRaises(ValueError):
            m.summary(lower=10, upper=5)

    def test_macro_gap_is_reported_not_distributed_to_families(self):
        external = self.report["external_benefit_comparison"]
        self.assertGreater(external["unallocated_difference"], 20e9)
        self.assertLess(external["unallocated_difference"], 23e9)
        self.assertAlmostEqual(external["model_benefits"], self.model.summary()["benefits"])

    def test_report_and_csv_export(self):
        # Public report is serialisable and export leaves the fitted model alone.
        json.dumps(self.report, allow_nan=False)
        before = self.model.summary()
        with tempfile.TemporaryDirectory() as directory:
            path = Path(directory) / "population.csv"
            self.model.write_csv(path)
            self.assertEqual(len(path.read_text().splitlines()), len(self.model.weights) + 1)
        self.assertEqual(before, self.model.summary())

    def test_source_metadata_and_raking(self):
        data = load_data()
        self.assertEqual(data["year"], "2019-20")
        for source in data["sources"].values():
            self.assertEqual(len(source["sha256"]), 64)
        matrix = rake([[1, 2], [3, 4]], [4, 6], [3, 7])
        np.testing.assert_allclose(matrix.sum(axis=1), [4, 6])
        np.testing.assert_allclose(matrix.sum(axis=0), [3, 7])
        with self.assertRaises(ValueError):
            rake([[1]], [2], [3])


if __name__ == "__main__":
    unittest.main()
