"""Tests for ACRS dispatch functionality."""

import json
import pytest
from unittest.mock import patch, MagicMock
from conftest import MockSession, MockLLM

from acrs_dispatch import dispatch_to_acrs


class TestDispatchToAcrs:
    """Tests for dispatch_to_acrs() function."""

    def _make_session(self, conversation_log=None, llm_response='{}'):
        return MockSession(
            conversation_log=conversation_log or [],
            llm=MockLLM(llm_response),
            llm_model='qwen3.5-flash',
            acrs_api_url='https://acrs.example.com/api',
            acrs_api_key='test-key',
            acrs_sp_account='admin',
            acrs_departments=[
                {'id': 1, 'name': 'Support', 'categories': [
                    {'id': 10, 'name': 'General'}
                ]}
            ],
            acrs_types=[{'id': 1, 'name': 'Inquiry'}],
            acrs_subcategories=[{'id': 1, 'name': 'Product'}],
            acrs_ratings=[{'id': 1, 'name': 'Good'}],
            acrs_custom_fields={'source': 'phone'},
            session_profile='test-profile',
        )

    def test_empty_conversation(self):
        session = self._make_session(conversation_log=[])
        result = dispatch_to_acrs(session)
        assert result['success'] is False
        assert 'No conversation' in result['message']

    @patch('acrs_dispatch.requests.post')
    def test_successful_dispatch(self, mock_post):
        mock_post.return_value = MagicMock(
            status_code=200,
            json=MagicMock(return_value={'caseNo': 'CASE-001'}),
            text='{"caseNo":"CASE-001"}'
        )
        llm_response = json.dumps({
            'departmentId': 1,
            'typeId': 1,
            'categoryId': 10,
            'subCategoryId': 1,
            'ratingId': 1,
            'summary': 'Product inquiry',
            'emailSubject': 'Product Question'
        })
        log = [
            {'speaker': 'caller', 'text': 'Tell me about mForce',
             'timestamp': '14:00:01'},
            {'speaker': 'AI', 'text': 'mForce helps manage field teams.',
             'timestamp': '14:00:05'},
        ]
        session = self._make_session(conversation_log=log,
                                     llm_response=llm_response)
        result = dispatch_to_acrs(session)
        assert result['success'] is True

    @patch('acrs_dispatch.requests.post')
    def test_payload_structure(self, mock_post):
        mock_post.return_value = MagicMock(
            status_code=200,
            json=MagicMock(return_value={}),
            text='{}'
        )
        llm_response = json.dumps({
            'departmentId': 1,
            'typeId': 1,
            'categoryId': 10,
            'subCategoryId': 1,
            'ratingId': 1,
            'summary': 'Test summary',
            'emailSubject': 'Test Subject'
        })
        log = [
            {'speaker': 'caller', 'text': 'Hello', 'timestamp': '14:00:01'},
        ]
        session = self._make_session(conversation_log=log,
                                     llm_response=llm_response)
        dispatch_to_acrs(session)

        call_args = mock_post.call_args
        payload = call_args[1].get('json') or call_args[0][1] if len(call_args[0]) > 1 else call_args[1].get('json')
        assert payload is not None
        assert payload['spAccount'] == 'admin'
        assert payload['departmentId'] == 1

    def test_llm_invalid_json(self):
        log = [
            {'speaker': 'caller', 'text': 'Hello', 'timestamp': '14:00:01'},
        ]
        session = self._make_session(
            conversation_log=log,
            llm_response='This is not valid JSON at all'
        )
        result = dispatch_to_acrs(session)
        assert result['success'] is False
        assert 'Classification failed' in result['message']

    @patch('acrs_dispatch.requests.post')
    def test_api_error(self, mock_post):
        mock_post.return_value = MagicMock(
            status_code=500,
            text='Internal Server Error',
            ok=False
        )
        llm_response = json.dumps({
            'departmentId': 1, 'typeId': 1, 'categoryId': 10,
            'subCategoryId': 1, 'ratingId': 1,
            'summary': 'Test', 'emailSubject': 'Test'
        })
        log = [
            {'speaker': 'caller', 'text': 'Hello', 'timestamp': '14:00:01'},
        ]
        session = self._make_session(conversation_log=log,
                                     llm_response=llm_response)
        result = dispatch_to_acrs(session)
        assert result['success'] is False

    @patch('acrs_dispatch.requests.post')
    def test_custom_fields_merged(self, mock_post):
        mock_post.return_value = MagicMock(
            status_code=200,
            json=MagicMock(return_value={}),
            text='{}'
        )
        llm_response = json.dumps({
            'departmentId': 1, 'typeId': 1, 'categoryId': 10,
            'subCategoryId': 1, 'ratingId': 1,
            'summary': 'Test', 'emailSubject': 'Test'
        })
        log = [
            {'speaker': 'caller', 'text': 'Hello', 'timestamp': '14:00:01'},
        ]
        session = self._make_session(conversation_log=log,
                                     llm_response=llm_response)
        dispatch_to_acrs(session)

        call_args = mock_post.call_args
        payload = call_args[1].get('json') or call_args[0][1]
        assert payload.get('source') == 'phone'
