import importlib.util
import os
import sqlite3
import tempfile
from collections import namedtuple
from unittest import skipUnless

from django.test import TestCase

from crop_simulation.services import CropSimulationService, PcseSimulationManager


@skipUnless(
    importlib.util.find_spec("pcse") is not None,
    "pcse must be installed to run the real WOFOST test.",
)
class CropSimulationSingleRunWithRecommendationsTest(TestCase):
    def test_single_simulation_with_irrigation_and_fertilization_recommendations(self):
        os.environ["HOME"] = tempfile.mkdtemp(prefix="pcse-home-", dir="/tmp")

        from pcse import settings as pcse_settings
        from pcse.tests.db_input import (
            AgroManagementDataProvider,
            GridWeatherDataProvider,
            fetch_cropdata,
            fetch_sitedata,
            fetch_soildata,
        )

        def namedtuple_factory(cursor, row):
            fields = [column[0] for column in cursor.description]
            cls = namedtuple("Row", fields)
            return cls._make(row)

        db_path = os.path.join(pcse_settings.PCSE_USER_HOME, "pcse.db")
        connection = sqlite3.connect(db_path)
        connection.row_factory = namedtuple_factory

        grid = int(os.environ.get("PCSE_TEST_GRID", "31031"))
        crop_no = int(os.environ.get("PCSE_TEST_CROP_NO", "1"))
        year = int(os.environ.get("PCSE_TEST_YEAR", "2000"))

        weather = GridWeatherDataProvider(connection, grid_no=grid).export()
        soil = fetch_soildata(connection, grid)
        site = fetch_sitedata(connection, grid, year)
        crop_parameters = fetch_cropdata(connection, grid, year, crop_no)
        agromanagement = AgroManagementDataProvider(connection, grid, crop_no, year)

        response = CropSimulationService(
            manager=PcseSimulationManager(model_name="Wofost72_WLP_CWB")
        ).run_single_simulation(
            weather=weather,
            soil=soil,
            crop_parameters=crop_parameters,
            agromanagement=agromanagement,
            site_parameters=site,
            irrigation_recommendation={
                "events": [
                    {"date": "2000-02-10", "amount": 2.5, "efficiency": 0.8},
                    {"date": "2000-03-05", "amount": 3.0, "efficiency": 0.8},
                ]
            },
            fertilization_recommendation={
                "events": [
                    {"date": "2000-02-15", "N_amount": 30, "N_recovery": 0.7},
                    {"date": "2000-03-01", "N_amount": 20, "N_recovery": 0.7},
                ]
            },
            name="single real wofost run with recommendations",
        )

        connection.close()
        print("\nCrop Simulation Response With Recommendations:\n", response)
        self.assertEqual(response["result"]["engine"], "pcse")
        self.assertIsNotNone(response["result"]["metrics"]["yield_estimate"])
        self.assertIsNotNone(response["result"]["metrics"]["biomass"])
