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 Rule, Scenario


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

    @classmethod
    def setUpClass(cls):
        super(RuleViewTest, 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_rule(self):
        response = self.client.post(
            reverse("rules"),
            {
                "rule-name": "Test Rule",
                "rule-description": "Just a Description",
                "rule-smirks": "[H:5][C:1]([#6:6])([#1,#9,#17,#35,#53:4])[#9,#17,#35,#53]>>[H:5][C:1]([#6:6])([#8])[#1,#9,#17,#35,#53:4]",
                "rule-type": "SimpleAmbitRule",
            },
        )

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

        r = Rule.objects.get(url=rule_url)

        self.assertEqual(r.package, self.user1_default_package)
        self.assertEqual(r.name, "Test Rule")
        self.assertEqual(r.description, "Just a Description")
        self.assertEqual(
            r.smirks,
            "[H:5][C:1]([#6:6])([#1,#9,#17,#35,#53:4])[#9,#17,#35,#53]>>[H:5][C:1]([#6:6])([#8])[#1,#9,#17,#35,#53:4]",
        )
        self.assertEqual(self.user1_default_package.rules.count(), 1)

        # Adding the same rule again should return the existing one, hence not increasing the number of rules
        response = self.client.post(
            reverse("rules"),
            {
                "rule-name": "Test Rule",
                "rule-description": "Just a Description",
                "rule-smirks": "[H:5][C:1]([#6:6])([#1,#9,#17,#35,#53:4])[#9,#17,#35,#53]>>[H:5][C:1]([#6:6])([#8])[#1,#9,#17,#35,#53:4]",
                "rule-type": "SimpleAmbitRule",
            },
        )

        self.assertEqual(response.url, rule_url)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(self.user1_default_package.rules.count(), 1)

        # Adding the same rule in a different package should create a new rule
        response = self.client.post(
            reverse("package rule list", kwargs={"package_uuid": self.package.uuid}),
            {
                "rule-name": "Test Rule",
                "rule-description": "Just a Description",
                "rule-smirks": "[H:5][C:1]([#6:6])([#1,#9,#17,#35,#53:4])[#9,#17,#35,#53]>>[H:5][C:1]([#6:6])([#8])[#1,#9,#17,#35,#53:4]",
                "rule-type": "SimpleAmbitRule",
            },
        )

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

    # Edit
    def test_edit_rule(self):
        response = self.client.post(
            reverse("rules"),
            {
                "rule-name": "Test Rule",
                "rule-description": "Just a Description",
                "rule-smirks": "[H:5][C:1]([#6:6])([#1,#9,#17,#35,#53:4])[#9,#17,#35,#53]>>[H:5][C:1]([#6:6])([#8])[#1,#9,#17,#35,#53:4]",
                "rule-type": "SimpleAmbitRule",
            },
        )

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

        r = Rule.objects.get(url=rule_url)

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

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

    # 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("rules"),
            {
                "rule-name": "Test Rule",
                "rule-description": "Just a Description",
                "rule-smirks": "[H:5][C:1]([#6:6])([#1,#9,#17,#35,#53:4])[#9,#17,#35,#53]>>[H:5][C:1]([#6:6])([#8])[#1,#9,#17,#35,#53:4]",
                "rule-type": "SimpleAmbitRule",
            },
        )

        self.assertEqual(response.status_code, 302)
        rule_url = response.url
        r = Rule.objects.get(url=rule_url)

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

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

        response = self.client.post(
            reverse(
                "package rule detail",
                kwargs={"package_uuid": str(r.package.uuid), "rule_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 rule detail",
                kwargs={"package_uuid": str(r.package.uuid), "rule_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("rules"),
            {
                "rule-name": "Test Rule",
                "rule-description": "Just a Description",
                "rule-smirks": "[H:5][C:1]([#6:6])([#1,#9,#17,#35,#53:4])[#9,#17,#35,#53]>>[H:5][C:1]([#6:6])([#8])[#1,#9,#17,#35,#53:4]",
                "rule-type": "SimpleAmbitRule",
            },
        )

        self.assertEqual(response.status_code, 302)
        rule_url = response.url
        r = Rule.objects.get(url=rule_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_rule = Rule.objects.get(url=copied_object_url)

        self.assertEqual(copied_rule.name, r.name)
        self.assertEqual(copied_rule.description, r.description)
        self.assertEqual(copied_rule.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 {rule_url} to the same package!"
        )

    def test_delete(self):
        response = self.client.post(
            reverse("rules"),
            {
                "rule-name": "Test Rule",
                "rule-description": "Just a Description",
                "rule-smirks": "[H:5][C:1]([#6:6])([#1,#9,#17,#35,#53:4])[#9,#17,#35,#53]>>[H:5][C:1]([#6:6])([#8])[#1,#9,#17,#35,#53:4]",
                "rule-type": "SimpleAmbitRule",
            },
        )
        self.assertEqual(response.status_code, 302)

        rule_url = response.url
        r = Rule.objects.get(url=rule_url)

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

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

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

        response = self.client.post(
            reverse("rules"),
            {
                "rule-name": "Test Rule",
                "rule-description": "Just a Description",
                "rule-smirks": "[H:5][C:1]([#6:6])([#1,#9,#17,#35,#53:4])[#9,#17,#35,#53]>>[H:5][C:1]([#6:6])([#8])[#1,#9,#17,#35,#53:4]",
                "rule-type": "SimpleAmbitRule",
            },
        )

        self.assertEqual(response.status_code, 302)
        rule_url = response.url
        r = Rule.objects.get(url=rule_url)

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

        r = Rule.objects.get(url=rule_url)
        self.assertEqual(len(r.aliases), 2)

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

        r = Rule.objects.get(url=rule_url)
        self.assertEqual(len(r.aliases), 1)

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

        r = Rule.objects.get(url=rule_url)
        self.assertEqual(len(r.aliases), 0)
