from django.conf import settings as s
from django.test import TestCase, override_settings
from django.urls import reverse
from envipy_additional_information import Temperature, Interval

from epdb.logic import UserManager, PackageManager
from epdb.models import Reaction, Scenario, ExternalDatabase


@override_settings(MODEL_DIR=s.FIXTURE_DIRS[0] / "models", CELERY_TASK_ALWAYS_EAGER=True)
class ReactionViewTest(TestCase):
    fixtures = ["test_fixtures_incl_model.jsonl.gz"]

    @classmethod
    def setUpClass(cls):
        super(ReactionViewTest, cls).setUpClass()
        cls.user1 = UserManager.create_user(
            "user1",
            "user1@envipath.com",
            "SuperSafe",
            set_setting=False,
            add_to_group=True,
            is_active=True,
        )
        cls.user1_default_package = cls.user1.default_package
        cls.package = PackageManager.create_package(cls.user1, "Test", "Test Pack")

    def setUp(self):
        self.client.force_login(self.user1)

    def test_create_reaction(self):
        response = self.client.post(
            reverse("reactions"),
            {
                "reaction-name": "Eawag BBD reaction r0001",
                "reaction-description": "Description for Eawag BBD reaction r0001",
                "reaction-smiles": "C(CCl)Cl>>C(CO)Cl",
            },
        )

        self.assertEqual(response.status_code, 302)
        reaction_url = response.url

        r = Reaction.objects.get(url=reaction_url)

        self.assertEqual(r.package, self.user1_default_package)
        self.assertEqual(r.name, "Eawag BBD reaction r0001")
        self.assertEqual(r.description, "Description for Eawag BBD reaction r0001")
        self.assertEqual(r.smirks(), "C(CCl)Cl>>C(CO)Cl")
        self.assertEqual(self.user1_default_package.reactions.count(), 1)

        # Adding the same rule again should return the existing one, hence not increasing the number of rules
        response = self.client.post(
            reverse("reactions"),
            {
                "reaction-name": "Eawag BBD reaction r0001",
                "reaction-description": "Description for Eawag BBD reaction r0001",
                "reaction-smiles": "C(CCl)Cl>>C(CO)Cl",
            },
        )

        self.assertEqual(response.url, reaction_url)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(self.user1_default_package.reactions.count(), 1)

        # Adding the same rule in a different package should create a new rule
        response = self.client.post(
            reverse("package reaction list", kwargs={"package_uuid": self.package.uuid}),
            {
                "reaction-name": "Eawag BBD reaction r0001",
                "reaction-description": "Description for Eawag BBD reaction r0001",
                "reaction-smiles": "C(CCl)Cl>>C(CO)Cl",
            },
        )

        self.assertEqual(response.status_code, 302)
        self.assertNotEqual(reaction_url, response.url)

        # adding another reaction should increase count
        response = self.client.post(
            reverse("reactions"),
            {
                "reaction-name": "Eawag BBD reaction r0002",
                "reaction-description": "Description for Eawag BBD reaction r0002",
                "reaction-smiles": "C(CO)Cl>>C(C=O)Cl",
            },
        )

        self.assertEqual(response.status_code, 302)
        self.assertEqual(self.user1_default_package.reactions.count(), 2)

    # Edit
    def test_edit_rule(self):
        response = self.client.post(
            reverse("reactions"),
            {
                "reaction-name": "Eawag BBD reaction r0001",
                "reaction-description": "Description for Eawag BBD reaction r0001",
                "reaction-smiles": "C(CCl)Cl>>C(CO)Cl",
            },
        )

        self.assertEqual(response.status_code, 302)
        reaction_url = response.url

        r = Reaction.objects.get(url=reaction_url)

        response = self.client.post(
            reverse(
                "package reaction detail",
                kwargs={
                    "package_uuid": str(self.user1_default_package.uuid),
                    "reaction_uuid": str(r.uuid),
                },
            ),
            {
                "reaction-name": "Test Reaction Adjusted",
                "reaction-description": "New Description",
            },
        )

        self.assertEqual(response.status_code, 302)
        r = Reaction.objects.get(url=reaction_url)
        self.assertEqual(r.name, "Test Reaction Adjusted")
        self.assertEqual(r.description, "New Description")

        # Rest stays untouched
        self.assertEqual(r.smirks(), "C(CCl)Cl>>C(CO)Cl")
        self.assertEqual(self.user1_default_package.reactions.count(), 1)

    # Scenario
    def test_set_scenario(self):
        s1 = Scenario.create(
            self.user1_default_package,
            "Test Scen",
            "Test Desc",
            "2025-10",
            "soil",
            [Temperature(interval=Interval(start=20, end=30))],
        )

        s2 = Scenario.create(
            self.user1_default_package,
            "Test Scen2",
            "Test Desc2",
            "2025-10",
            "soil",
            [Temperature(interval=Interval(start=10, end=20))],
        )

        response = self.client.post(
            reverse("reactions"),
            {
                "reaction-name": "Eawag BBD reaction r0001",
                "reaction-description": "Description for Eawag BBD reaction r0001",
                "reaction-smiles": "C(CCl)Cl>>C(CO)Cl",
            },
        )

        self.assertEqual(response.status_code, 302)
        reaction_url = response.url
        r = Reaction.objects.get(url=reaction_url)

        response = self.client.post(
            reverse(
                "package reaction detail",
                kwargs={"package_uuid": str(r.package.uuid), "reaction_uuid": str(r.uuid)},
            ),
            {"selected-scenarios": [s1.url, s2.url]},
        )

        self.assertEqual(len(r.scenarios.all()), 2)

        response = self.client.post(
            reverse(
                "package reaction detail",
                kwargs={"package_uuid": str(r.package.uuid), "reaction_uuid": str(r.uuid)},
            ),
            {"selected-scenarios": [s1.url]},
        )

        self.assertEqual(len(r.scenarios.all()), 1)
        self.assertEqual(r.scenarios.first().url, s1.url)

        response = self.client.post(
            reverse(
                "package reaction detail",
                kwargs={"package_uuid": str(r.package.uuid), "reaction_uuid": str(r.uuid)},
            ),
            {
                # We have to set an empty string to avoid that the parameter is removed
                "selected-scenarios": ""
            },
        )

        self.assertEqual(len(r.scenarios.all()), 0)

    def test_copy(self):
        response = self.client.post(
            reverse("reactions"),
            {
                "reaction-name": "Eawag BBD reaction r0001",
                "reaction-description": "Description for Eawag BBD reaction r0001",
                "reaction-smiles": "C(CCl)Cl>>C(CO)Cl",
            },
        )

        self.assertEqual(response.status_code, 302)
        reaction_url = response.url
        r = Reaction.objects.get(url=reaction_url)

        response = self.client.post(
            reverse(
                "package detail",
                kwargs={
                    "package_uuid": str(self.package.uuid),
                },
            ),
            {"hidden": "copy", "object_to_copy": r.url},
        )

        self.assertEqual(response.status_code, 200)

        copied_object_url = response.json()["success"]
        copied_reaction = Reaction.objects.get(url=copied_object_url)

        self.assertEqual(copied_reaction.name, r.name)
        self.assertEqual(copied_reaction.description, r.description)
        self.assertEqual(copied_reaction.smirks(), r.smirks())

        # Copy to the same package should fail
        response = self.client.post(
            reverse(
                "package detail",
                kwargs={
                    "package_uuid": str(r.package.uuid),
                },
            ),
            {"hidden": "copy", "object_to_copy": r.url},
        )

        self.assertEqual(response.status_code, 400)
        self.assertEqual(
            response.json()["error"], f"Can't copy object {reaction_url} to the same package!"
        )

    def test_references(self):
        ext_db, _ = ExternalDatabase.objects.get_or_create(
            name="KEGG Reaction",
            defaults={
                "full_name": "KEGG Reaction Database",
                "description": "Database of biochemical reactions",
                "base_url": "https://www.genome.jp",
                "url_pattern": "https://www.genome.jp/entry/{id}",
            },
        )

        ext_db2, _ = ExternalDatabase.objects.get_or_create(
            name="RHEA",
            defaults={
                "full_name": "RHEA Reaction Database",
                "description": "Comprehensive resource of biochemical reactions",
                "base_url": "https://www.rhea-db.org",
                "url_pattern": "https://www.rhea-db.org/rhea/{id}",
            },
        )

        response = self.client.post(
            reverse("reactions"),
            {
                "reaction-name": "Eawag BBD reaction r0001",
                "reaction-description": "Description for Eawag BBD reaction r0001",
                "reaction-smiles": "C(CCl)Cl>>C(CO)Cl",
            },
        )

        self.assertEqual(response.status_code, 302)
        reaction_url = response.url
        r = Reaction.objects.get(url=reaction_url)

        response = self.client.post(
            reverse(
                "package reaction detail",
                kwargs={
                    "package_uuid": str(r.package.uuid),
                    "reaction_uuid": str(r.uuid),
                },
            ),
            {"selected-database": ext_db.pk, "identifier": "C12345"},
        )

        self.assertEqual(r.external_identifiers.count(), 1)
        self.assertEqual(r.external_identifiers.first().database, ext_db)
        self.assertEqual(r.external_identifiers.first().identifier_value, "C12345")
        # TODO Fixture contains old url template there the real test fails, use old value instead
        # self.assertEqual(r.external_identifiers.first().url, 'https://www.genome.jp/entry/C12345')
        self.assertEqual(
            r.external_identifiers.first().url, "https://www.genome.jp/entry/reaction+C12345"
        )

        response = self.client.post(
            reverse(
                "package reaction detail",
                kwargs={
                    "package_uuid": str(r.package.uuid),
                    "reaction_uuid": str(r.uuid),
                },
            ),
            {"selected-database": ext_db2.pk, "identifier": "60116"},
        )

        self.assertEqual(r.external_identifiers.count(), 2)
        self.assertEqual(r.external_identifiers.last().database, ext_db2)
        self.assertEqual(r.external_identifiers.last().identifier_value, "60116")
        self.assertEqual(r.external_identifiers.last().url, "https://www.rhea-db.org/rhea/60116")

    def test_delete(self):
        response = self.client.post(
            reverse("reactions"),
            {
                "reaction-name": "Eawag BBD reaction r0001",
                "reaction-description": "Description for Eawag BBD reaction r0001",
                "reaction-smiles": "C(CCl)Cl>>C(CO)Cl",
            },
        )
        self.assertEqual(response.status_code, 302)

        reaction_url = response.url
        r = Reaction.objects.get(url=reaction_url)

        response = self.client.post(
            reverse(
                "package reaction detail",
                kwargs={"package_uuid": str(r.package.uuid), "reaction_uuid": str(r.uuid)},
            ),
            {"hidden": "delete"},
        )

        self.assertEqual(self.user1_default_package.reactions.count(), 0)

    def test_set_aliases(self):
        alias_1 = "Alias 1"
        alias_2 = "Alias 2"

        response = self.client.post(
            reverse("reactions"),
            {
                "reaction-name": "Eawag BBD reaction r0001",
                "reaction-description": "Description for Eawag BBD reaction r0001",
                "reaction-smiles": "C(CCl)Cl>>C(CO)Cl",
            },
        )

        self.assertEqual(response.status_code, 302)
        reaction_url = response.url
        r = Reaction.objects.get(url=reaction_url)

        response = self.client.post(
            reverse(
                "package reaction detail",
                kwargs={"package_uuid": str(r.package.uuid), "reaction_uuid": str(r.uuid)},
            ),
            {"aliases": [alias_1, alias_2]},
        )

        r = Reaction.objects.get(url=reaction_url)
        self.assertEqual(len(r.aliases), 2)

        response = self.client.post(
            reverse(
                "package reaction detail",
                kwargs={"package_uuid": str(r.package.uuid), "reaction_uuid": str(r.uuid)},
            ),
            {"aliases": [alias_1]},
        )

        r = Reaction.objects.get(url=reaction_url)
        self.assertEqual(len(r.aliases), 1)

        response = self.client.post(
            reverse(
                "package reaction detail",
                kwargs={"package_uuid": str(r.package.uuid), "reaction_uuid": str(r.uuid)},
            ),
            {
                # We have to set an empty string to avoid that the parameter is removed
                "aliases": ""
            },
        )

        r = Reaction.objects.get(url=reaction_url)
        self.assertEqual(len(r.aliases), 0)
