"""Shared fixtures, mock helpers, and sample data for AI-PHONE tests."""

import sys
import os
import json
import pytest

# Add project root to path so we can import modules
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


# ── Mock helpers ──────────────────────────────────────────────────

class MockChoice:
    def __init__(self, content):
        self.message = type('obj', (object,), {'content': content})()


class MockChatResponse:
    def __init__(self, content):
        self.choices = [MockChoice(content)]


class MockCompletions:
    def __init__(self, response_content=''):
        self._response_content = response_content

    def create(self, **kwargs):
        return MockChatResponse(self._response_content)


class MockChat:
    def __init__(self, response_content=''):
        self.completions = MockCompletions(response_content)


class MockLLM:
    """Mock OpenAI-compatible LLM client."""
    def __init__(self, response_content=''):
        self.chat = MockChat(response_content)


class MockSession:
    """Lightweight mock PipelineSession with configurable attributes."""
    def __init__(self, **kwargs):
        # Defaults
        self.extensions_directory = []
        self.agent_data = ''
        self.conversation_log = []
        self.llm = MockLLM()
        self.llm_model = 'qwen3.5-flash'
        self.cv_enabled = False
        self.cv_api_url = ''
        self.cv_api_key = ''
        self.omni_model = 'qwen3.5-omni-plus-realtime'
        self.omni_mode = True
        self.active_agent = 'a'
        self.agents = {'a': {'name': 'Receptionist', 'history': []}}
        self.custom_tools = []
        self.transfer_agents_enabled = False
        self.language_agent_enabled = False
        self.supported_languages = ['en', 'zh', 'ms']
        self.session_language = 'en'
        self.session_profile = 'test-profile'
        self.omni_speech_style = ''
        self._omni_usage_totals = {
            'input_text_tokens': 0,
            'input_audio_tokens': 0,
            'output_text_tokens': 0,
            'output_audio_tokens': 0,
            'turns': 0,
        }
        # Pre-emit buffer
        self._omni_pre_emit_buffer = []
        self._omni_pre_emit_gen = 0
        self._omni_pre_emit_timer = None
        self._omni_pre_emit_buffering = False
        self._omni_audio_buffer_delay = 0.3
        # ACRS config
        self.acrs_enabled = False
        self.acrs_api_url = ''
        self.acrs_api_key = ''
        self.acrs_sp_account = 'admin'
        self.acrs_departments = []
        self.acrs_types = []
        self.acrs_subcategories = []
        self.acrs_ratings = []
        self.acrs_custom_fields = {}
        # Override with kwargs
        for k, v in kwargs.items():
            setattr(self, k, v)

    def _log_message(self, speaker, text):
        pass


# ── Sample data fixtures ─────────────────────────────────────────

@pytest.fixture
def sample_extensions():
    """Structured extension list matching the user's real data."""
    return [
        {'name': 'Benny Toh', 'department': 'Management', 'ext': '8000',
         'status': 'ONLINE', 'hours': '09:00-22:00', 'autoAnswer': False},
        {'name': 'Askey Puah', 'department': 'Technical Department'},
        {'name': 'Mohamad Shazwan', 'department': 'Mobile Team'},
        {'name': 'Tan Kar Khim', 'department': 'Mobile Team'},
        {'name': 'Jacky Su', 'department': 'Mobile Team'},
        {'name': 'Yap Zhan Yong', 'department': 'Web Application Team'},
        {'name': 'Haja Mydeen', 'department': 'DotNet Team'},
        {'name': 'Lin Naing', 'department': 'DotNet Team'},
        {'name': 'John Kum', 'department': 'DMS Team'},
        {'name': 'Jonathan Yong', 'department': 'DMS Team'},
        {'name': 'John Hoo', 'department': 'Systems Administrator'},
        {'name': 'Frank Chee', 'department': 'Database Administrator'},
        {'name': 'Mon', 'department': 'Product Team'},
        {'name': 'Kevin Koh', 'department': 'Product Team'},
        {'name': 'Samuel Foo', 'department': 'Product Team'},
        {'name': 'Timmy Ting', 'department': 'Client Service Delivery', 'ext': '8500',
         'status': 'ONLINE', 'hours': '07:00-17:00', 'autoAnswer': False},
        {'name': 'Nur Fatin', 'department': 'Client Service Delivery'},
        {'name': 'Nurul Nailah', 'department': 'Client Service Delivery'},
        {'name': 'Afifah', 'department': 'Client Service Delivery'},
        {'name': 'Allen Cheong', 'department': 'Client Service Delivery'},
        {'name': 'Melvan Liang', 'department': 'Business Intelligent'},
        {'name': 'Xin Yi', 'department': 'Business Intelligent'},
        {'name': 'Shoban', 'department': 'Artificial Intelligent (AI)', 'leader': True},
        {'name': 'Joanne Chen', 'department': 'Artificial Intelligent (AI)'},
        {'name': 'Jeremy Ng', 'department': 'Artificial Intelligent (AI)', 'ext': '8702',
         'status': 'OFFLINE', 'hours': '09:00-17:00', 'autoAnswer': False},
        {'name': 'Zack Jong', 'department': 'Artificial Intelligent (AI)', 'ext': '8703',
         'status': 'ONLINE', 'hours': '09:00-17:00', 'autoAnswer': False},
        {'name': 'Soon Keat', 'department': 'Artificial Intelligent (AI)'},
        {'name': 'Lai Jun Yan', 'department': 'Artificial Intelligent (AI)'},
        {'name': 'May', 'department': 'Accounts & Finance'},
        {'name': 'Kristin Tan', 'department': 'Sales Ops Support and Admin'},
        {'name': 'Lai Leng', 'department': 'Accounts'},
    ]


@pytest.fixture
def sample_legacy_agent_data():
    """Full old-format agent_data text as sent by Asterisk."""
    return (
        "EXTENSIONS DIRECTORY:\n"
        "- Benny Toh (Management): ext 8000, autoAnswer=no\n"
        "- Askey Puah (Technical Department)\n"
        "- Mohamad Shazwan (Mobile Team)\n"
        "- Tan Kar Khim (Mobile Team)\n"
        "- Jacky Su (Mobile Team)\n"
        "- Yap Zhan Yong (Web Application Team)\n"
        "- Haja Mydeen (DotNet Team)\n"
        "- Lin Naing (DotNet Team)\n"
        "- John Kum (DMS Team)\n"
        "- Jonathan Yong (DMS Team)\n"
        "- John Hoo (Systems Administrator)\n"
        "- Frank Chee (Database Administrator)\n"
        "- Mon (Product Team)\n"
        "- Kevin Koh (Product Team)\n"
        "- Samuel Foo (Product Team)\n"
        "- Timmy Ting (Client Service Delivery): ext 8500, autoAnswer=no\n"
        "- Nur Fatin (Client Service Delivery)\n"
        "- Nurul Nailah (Client Service Delivery)\n"
        "- Afifah (Client Service Delivery)\n"
        "- Allen Cheong (Client Service Delivery)\n"
        "- Melvan Liang (Business Intelligent)\n"
        "- Xin Yi (Business Intelligent)\n"
        "- Shoban (Artificial Intelligent (AI))\n"
        "- Joanne Chen (Artificial Intelligent (AI))\n"
        "- Jeremy Ng (Artificial Intelligent (AI)): ext 8702, autoAnswer=no\n"
        "- Zack Jong (Artificial Intelligent (AI)): ext 8703, autoAnswer=no\n"
        "- Soon Keat (Artificial Intelligent (AI))\n"
        "- Lai Jun Yan (Artificial Intelligent (AI))\n"
        "- May (Accounts & Finance)\n"
        "- Kristin Tan (Sales Ops Support and Admin)\n"
        "- Lai Leng (Accounts)\n"
        "\n"
        "EXTENSION STATUS (check AFTER confirming the person with the caller):\n"
        "- ext 8000: [ONLINE] hours 09:00-22:00\n"
        "- ext 8500: [ONLINE] hours 07:00-17:00\n"
        "- ext 8702: [OFFLINE] hours 09:00-17:00\n"
        "- ext 8703: [ONLINE] hours 09:00-17:00\n"
        "\n"
        "STATUS KEY:\n"
        "[ONLINE] = available\n"
        "[OUTSIDE HOURS] = outside working hours\n"
        "[OFFLINE] = phone off\n"
        "[BUSY] = on another call\n"
        "[NOT REGISTERED] = not set up\n"
        "\n"
        "CURRENT TIME: Thursday 16:30\n"
        "CALLER PHONE: unknown"
    )


@pytest.fixture
def sample_conversation_log():
    """Sample conversation log for validator/ACRS tests."""
    return [
        {'speaker': 'AI', 'text': 'Hello, how may I help you?', 'timestamp': '14:02:37'},
        {'speaker': 'caller', 'text': 'Can you tell me about your products?', 'timestamp': '14:02:45'},
        {'speaker': 'AI', 'text': 'We have mForce, mFlux, mTrade, and mSmart.', 'timestamp': '14:02:49'},
        {'speaker': 'caller', 'text': "I'd like to know more about mForce.", 'timestamp': '14:02:53'},
        {'speaker': 'AI', 'text': 'mForce helps manage field teams. Want to speak with an expert?', 'timestamp': '14:02:57'},
        {'speaker': 'caller', 'text': 'Yes please.', 'timestamp': '14:03:09'},
        {'speaker': 'AI', 'text': "I'm transferring you now.", 'timestamp': '14:03:11'},
    ]


@pytest.fixture
def sample_profile_data():
    """Sample ChromaDB profile data with all special fields."""
    return {
        'agentAName': 'Serena',
        'llmModel': 'qwen3.5-flash',
        'temperature': '0.7',
        'maxTokens': '150',
        'topP': '0.9',
        'enableOmni': True,
        'omniModel': 'qwen3.5-omni-plus-realtime',
        'vadThreshold': '0.5',
        'silenceDuration': '700',
        'bargeInEnabled': True,
        'speechRate': '1.0',
        'pitchRate': '1.0',
        'ttsVolume': '50',
        'fixedGreeting': json.dumps({'en': 'Hello!', 'zh': '你好！'}),
        'instructions': 'You are a receptionist.',
        'voiceMap': json.dumps({'en': 'Ethan', 'zh': 'Cherry'}),
        'acrs': json.dumps({
            'enabled': True,
            'api_url': 'https://acrs.example.com/api',
            'api_key': 'test-key',
        }),
        'conversationValidator': json.dumps({
            'enabled': True,
            'api_url': 'https://validator.example.com/validate',
            'api_key': 'cv-key',
        }),
        'emotionConfig': json.dumps({
            'enabled': False,
            'engine_url': 'ws://localhost:8769',
        }),
        'functionsTextarea': json.dumps([
            {'type': 'function', 'function': {'name': 'test_tool', 'parameters': {}}}
        ]),
        'transferAgents': json.dumps([
            {'name': 'Sales', 'instructions': 'Help with sales.'}
        ]),
        'allowedLanguages': json.dumps(['en', 'zh', 'ms']),
    }
