from django.test import TestCase, override_settings
from rest_framework.test import APIClient

from location_data.models import AnalysisGridCell, BlockSubdivision, RemoteSensingRun, SoilLocation


@override_settings(ROOT_URLCONF="location_data.urls")
class SoilDataApiTests(TestCase):
    def setUp(self):
        self.client = APIClient()
        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],
                ]
            ],
        }
        self.block_boundary = {
            "type": "Polygon",
            "coordinates": [
                [
                    [51.3890, 35.6890],
                    [51.3896, 35.6890],
                    [51.3896, 35.6900],
                    [51.3890, 35.6900],
                    [51.3890, 35.6890],
                ]
            ],
        }

    def test_post_creates_default_single_block_layout(self):
        response = self.client.post(
            "/",
            data={
                "lat": 35.6892,
                "lon": 51.3890,
                "farm_boundary": self.boundary,
                "blocks": [
                    {
                        "block_code": "block-1",
                        "boundary": self.block_boundary,
                    }
                ],
            },
            format="json",
        )

        self.assertEqual(response.status_code, 200)
        payload = response.json()["data"]
        self.assertEqual(payload["source"], "created")
        self.assertEqual(payload["input_block_count"], 1)
        self.assertEqual(len(payload["block_layout"]["blocks"]), 1)
        self.assertEqual(payload["block_layout"]["blocks"][0]["boundary"], self.block_boundary)
        self.assertEqual(payload["block_layout"]["algorithm_status"], "pending")
        self.assertEqual(len(payload["block_layout"]["blocks"][0]["sub_blocks"]), 1)
        self.assertEqual(payload["block_layout"]["blocks"][0]["sub_blocks"][0]["sub_block_code"], "block-1-sub-1")
        self.assertEqual(payload["block_layout"]["blocks"][0]["sub_blocks"][0]["cluster_label"], 0)
        self.assertEqual(len(payload["block_subdivisions"]), 1)
        self.assertEqual(payload["block_subdivisions"][0]["status"], "defined")
        self.assertEqual(payload["satellite_snapshots"][0]["status"], "missing")

    def test_model_default_layout_includes_default_sub_block_when_missing(self):
        location = SoilLocation.objects.create(
            latitude="35.689201",
            longitude="51.389001",
        )

        self.assertEqual(location.input_block_count, 1)
        self.assertEqual(location.block_layout["blocks"][0]["block_code"], "block-1")
        self.assertEqual(len(location.block_layout["blocks"][0]["sub_blocks"]), 1)
        self.assertEqual(
            location.block_layout["blocks"][0]["sub_blocks"][0]["sub_block_code"],
            "block-1-sub-1",
        )
        self.assertEqual(location.block_layout["blocks"][0]["sub_blocks"][0]["source"], "default")


    def test_post_updates_block_layout_from_input(self):
        SoilLocation.objects.create(
            latitude="35.689200",
            longitude="51.389000",
        )

        response = self.client.post(
            "/",
            data={
                "lat": 35.6892,
                "lon": 51.3890,
                "farm_boundary": self.boundary,
                "blocks": [
                    {"block_code": "block-a", "boundary": self.block_boundary},
                    {"block_code": "block-b", "boundary": self.block_boundary},
                ],
            },
            format="json",
        )

        self.assertEqual(response.status_code, 200)
        payload = response.json()["data"]
        self.assertEqual(payload["input_block_count"], 2)
        self.assertEqual(len(payload["block_layout"]["blocks"]), 2)
        self.assertEqual(len(payload["block_subdivisions"]), 2)

        location = SoilLocation.objects.get(latitude="35.689200", longitude="51.389000")
        self.assertEqual(location.input_block_count, 2)
        self.assertEqual(len(location.block_layout["blocks"]), 2)
        self.assertEqual(location.block_layout["algorithm_status"], "pending")
        self.assertTrue(
            BlockSubdivision.objects.filter(
                soil_location=location,
                block_code="block-a",
                status="defined",
            ).exists()
        )

    def test_get_returns_stored_subdivisions_without_processing(self):
        self.client.post(
            "/",
            data={
                "lat": 35.6892,
                "lon": 51.3890,
                "farm_boundary": self.boundary,
                "blocks": [
                    {
                        "block_code": "block-1",
                        "boundary": self.block_boundary,
                    }
                ],
            },
            format="json",
        )

        response = self.client.get(
            "/",
            data={"lat": 35.6892, "lon": 51.3890},
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json()["data"]["source"], "database")
        self.assertEqual(len(response.json()["data"]["block_subdivisions"]), 1)

    def test_post_removes_blocks_not_present_in_latest_farmer_input(self):
        self.client.post(
            "/",
            data={
                "lat": 35.6892,
                "lon": 51.3890,
                "farm_boundary": self.boundary,
                "blocks": [
                    {"block_code": "block-a", "boundary": self.block_boundary},
                    {"block_code": "block-b", "boundary": self.block_boundary},
                ],
            },
            format="json",
        )

        response = self.client.post(
            "/",
            data={
                "lat": 35.6892,
                "lon": 51.3890,
                "farm_boundary": self.boundary,
                "blocks": [
                    {"block_code": "block-a", "boundary": self.block_boundary},
                ],
            },
            format="json",
        )

        self.assertEqual(response.status_code, 200)
        payload = response.json()["data"]
        self.assertEqual(len(payload["block_subdivisions"]), 1)
        self.assertEqual(payload["block_subdivisions"][0]["block_code"], "block-a")

        location = SoilLocation.objects.get(latitude="35.689200", longitude="51.389000")
        self.assertTrue(
            BlockSubdivision.objects.filter(soil_location=location, block_code="block-a").exists()
        )
        self.assertFalse(
            BlockSubdivision.objects.filter(soil_location=location, block_code="block-b").exists()
        )

    def test_post_clears_cached_grid_and_run_when_block_boundary_changes(self):
        self.client.post(
            "/",
            data={
                "lat": 35.6892,
                "lon": 51.3890,
                "farm_boundary": self.boundary,
                "blocks": [
                    {"block_code": "block-1", "boundary": self.block_boundary},
                ],
            },
            format="json",
        )
        location = SoilLocation.objects.get(latitude="35.689200", longitude="51.389000")
        subdivision = BlockSubdivision.objects.get(soil_location=location, block_code="block-1")
        AnalysisGridCell.objects.create(
            soil_location=location,
            block_subdivision=subdivision,
            block_code="block-1",
            cell_code="cell-1",
            chunk_size_sqm=900,
            geometry=self.block_boundary,
            centroid_lat="35.689500",
            centroid_lon="51.389300",
        )
        RemoteSensingRun.objects.create(
            soil_location=location,
            block_subdivision=subdivision,
            block_code="block-1",
            chunk_size_sqm=900,
            temporal_start="2025-01-01",
            temporal_end="2025-01-31",
            status=RemoteSensingRun.STATUS_SUCCESS,
        )
        subdivision.grid_points = [{"cell_code": "cell-1"}]
        subdivision.centroid_points = [{"sub_block_code": "cluster-0"}]
        subdivision.grid_point_count = 1
        subdivision.centroid_count = 1
        subdivision.status = "subdivided"
        subdivision.save(
            update_fields=[
                "grid_points",
                "centroid_points",
                "grid_point_count",
                "centroid_count",
                "status",
                "updated_at",
            ]
        )

        updated_boundary = {
            "type": "Polygon",
            "coordinates": [
                [
                    [51.3892, 35.6890],
                    [51.3898, 35.6890],
                    [51.3898, 35.6900],
                    [51.3892, 35.6900],
                    [51.3892, 35.6890],
                ]
            ],
        }
        response = self.client.post(
            "/",
            data={
                "lat": 35.6892,
                "lon": 51.3890,
                "farm_boundary": self.boundary,
                "blocks": [
                    {"block_code": "block-1", "boundary": updated_boundary},
                ],
            },
            format="json",
        )

        self.assertEqual(response.status_code, 200)
        subdivision.refresh_from_db()
        self.assertEqual(subdivision.status, "defined")
        self.assertEqual(subdivision.source_boundary, updated_boundary)
        self.assertEqual(subdivision.grid_points, [])
        self.assertEqual(subdivision.centroid_points, [])
        self.assertEqual(subdivision.grid_point_count, 0)
        self.assertEqual(subdivision.centroid_count, 0)
        self.assertFalse(
            AnalysisGridCell.objects.filter(soil_location=location, block_code="block-1").exists()
        )
        self.assertFalse(
            RemoteSensingRun.objects.filter(soil_location=location, block_code="block-1").exists()
        )
