from __future__ import annotations

from django.test import TestCase
from django.urls import reverse

from core.commands.policies import ensure_variant_policies_for_profile
from core.models import CommandProfile, User


class CommandRoutingVariantUITests(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            username="routing-user",
            email="routing@example.com",
            password="x",
        )
        self.client.force_login(self.user)
        self.profile = CommandProfile.objects.create(
            user=self.user,
            slug="bp",
            name="Business Plan",
            enabled=True,
            trigger_token="#bp#",
            reply_required=True,
            exact_match_only=True,
        )
        ensure_variant_policies_for_profile(self.profile)

    def test_command_routing_page_shows_variant_policy_table(self):
        response = self.client.get(reverse("command_routing"))
        self.assertEqual(200, response.status_code)
        self.assertContains(response, "Variant Policies")
        self.assertContains(response, "bp set range")
        self.assertContains(response, "Send status to egress")
        self.assertContains(response, "Business Plan (bp)")

    def test_variant_policy_update_persists(self):
        response = self.client.post(
            reverse("command_routing"),
            {
                "action": "variant_policy_update",
                "profile_id": str(self.profile.id),
                "variant_key": "bp_set",
                "enabled": "1",
                "generation_mode": "ai",
                "send_plan_to_egress": "1",
                "send_status_to_source": "1",
                "send_status_to_egress": "1",
            },
            follow=True,
        )
        self.assertEqual(200, response.status_code)
        row = self.profile.variant_policies.get(variant_key="bp_set")
        self.assertEqual("ai", row.generation_mode)
        self.assertTrue(row.send_status_to_egress)

    def test_variant_policy_update_preserves_source_status_toggle(self):
        response = self.client.post(
            reverse("command_routing"),
            {
                "action": "variant_policy_update",
                "profile_id": str(self.profile.id),
                "variant_key": "bp_set",
                "enabled": "1",
                "generation_mode": "verbatim",
                # Intentionally omit send_status_to_source to set it False.
            },
            follow=True,
        )
        self.assertEqual(200, response.status_code)
        row = self.profile.variant_policies.get(variant_key="bp_set")
        self.assertFalse(row.send_status_to_source)

        # Rendering the page should not overwrite user policy decisions.
        response = self.client.get(reverse("command_routing"))
        self.assertEqual(200, response.status_code)
        row.refresh_from_db()
        self.assertFalse(row.send_status_to_source)
