from django.test import SimpleTestCase, override_settings

from location_data.block_subdivision import (
    build_block_subdivision_payload,
    detect_elbow_point,
)


@override_settings(SUBDIVISION_CHUNK_SQM=900)
class BlockSubdivisionServiceTests(SimpleTestCase):
    def test_detect_elbow_point_from_sse_curve(self):
        inertia_curve = [
            {"k": 1, "sse": 1000.0},
            {"k": 2, "sse": 400.0},
            {"k": 3, "sse": 220.0},
            {"k": 4, "sse": 180.0},
        ]

        optimal_k = detect_elbow_point(inertia_curve)

        self.assertEqual(optimal_k, 2)

    def test_build_block_subdivision_payload_returns_grid_and_centroids(self):
        boundary = {
            "type": "Polygon",
            "coordinates": [
                [
                    [51.3890, 35.6890],
                    [51.3902, 35.6890],
                    [51.3902, 35.6900],
                    [51.3890, 35.6900],
                    [51.3890, 35.6890],
                ]
            ],
        }

        result = build_block_subdivision_payload(boundary, block_code="block-1")

        self.assertEqual(result["block_code"], "block-1")
        self.assertEqual(result["chunk_size_sqm"], 900)
        self.assertGreater(result["grid_point_count"], 0)
        self.assertGreater(result["centroid_count"], 0)
        self.assertIn("optimal_k", result["metadata"])
        self.assertTrue(result["metadata"]["inertia_curve"])
