from asgiref.sync import async_to_sync
from django.contrib.auth import get_user_model
from django.test import TestCase

from apps.accounts.models import Organization, Role
from apps.onboarding.consumers import OnboardingConsumer
from apps.onboarding.models import AgentConfig

User = get_user_model()


class OnboardingConsumerConfigSelectionTests(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            email_address='consumer-test@example.com',
            password='pass1234',
            first_name='Consumer',
            last_name='Tester',
            date_of_birth='1992-02-02',
            is_manager=True,
        )
        self.org = Organization.objects.create(name='Consumer Test Org', owner=self.user)
        self.org.members.add(self.user)

        self.quant_role = Role.objects.create(name='Quant Role Consumer', organization=self.org)
        self.ux_role = Role.objects.create(name='UX Role Consumer', organization=self.org)

        self.consumer = OnboardingConsumer()

    def test_get_config_by_type_prefers_exact_role(self):
        quant_cfg = AgentConfig.objects.create(
            organization=self.org,
            role=self.quant_role,
            name='Quant Curriculum Override',
            agent_type='curriculum',
            system_prompt='Quant-specific prompt',
        )
        AgentConfig.objects.create(
            organization=self.org,
            role=self.ux_role,
            name='UX Curriculum Override',
            agent_type='curriculum',
            system_prompt='UX-specific prompt',
        )

        selected = async_to_sync(self.consumer.get_config_by_type)(str(self.quant_role.uuid), 'curriculum')

        self.assertIsNotNone(selected)
        self.assertEqual(selected.uuid, quant_cfg.uuid)
        self.assertEqual(selected.role_id, self.quant_role.id)

    def test_get_config_by_type_falls_back_to_org_default(self):
        AgentConfig.objects.filter(role=self.quant_role, agent_type='monitor').delete()

        org_default = AgentConfig.objects.create(
            organization=self.org,
            role=None,
            name='Org Monitor Default',
            agent_type='monitor',
            system_prompt='Organization-level monitor prompt',
        )

        selected = async_to_sync(self.consumer.get_config_by_type)(str(self.quant_role.uuid), 'monitor')

        self.assertIsNotNone(selected)
        self.assertEqual(selected.uuid, org_default.uuid)
        self.assertIsNone(selected.role)

    def test_extract_json_list_supports_wrapped_questions_payload(self):
        payload = (
            "Here is your quiz output:\n"
            "```json\n"
            '{"questions": [{"key": "q1", "label": "Question?", "field_type": "select", "options": ["A", "B"], "required": true, "validation": {"correct_option": "A", "explanation": "A"}}]}\n'
            "```"
        )

        extracted = self.consumer._extract_json_list(payload)

        self.assertIsInstance(extracted, list)
        self.assertEqual(len(extracted), 1)
        self.assertEqual(extracted[0]['key'], 'q1')

    def test_build_fallback_quiz_fields_generates_eight_valid_questions(self):
        fallback = self.consumer._build_fallback_quiz_fields(['Topic A', 'Topic B'])

        self.assertEqual(len(fallback), 8)
        self.assertTrue(all(item.get('field_type') == 'select' for item in fallback))
        self.assertTrue(all(len(item.get('options', [])) >= 4 for item in fallback))
        self.assertTrue(all(item.get('validation', {}).get('correct_option') in item.get('options', []) for item in fallback))
