"""
E2E Full User Journey Tests.

Simulates complete user workflows based on:
- /mnt/e/genesis-system/RECEPTIONISTAI/DEMO_RECORDING_SUMMARY.md
- /mnt/e/genesis-system/Conversations/gemini_ultra_plan_features_extracted.md
"""
import pytest
from playwright.sync_api import expect


class TestCompleteUserJourney:
    """Full end-to-end user journey scenarios."""

    def test_first_time_visitor_journey(self, page, widget_url):
        """
        Test: New visitor lands on demo page -> opens widget -> sends message.

        User Story: As a first-time visitor, I want to quickly test
        the chat widget to see how it works.
        """
        # 1. Land on demo page
        page.goto(f"{widget_url}/demo.html")
        page.wait_for_load_state("networkidle")

        # 2. Page should be loaded and visible
        expect(page.locator('body')).to_be_visible()

        # 3. User sees the widget trigger button
        trigger = page.locator('button.widget-trigger, button[aria-label*="call"]').first
        expect(trigger).to_be_visible()

        # 4. User clicks to open widget
        trigger.click()
        page.wait_for_timeout(1000)

        # 5. Chat interface opens
        chat_interface = page.locator('.chat-interface, .chat-window, .message-container')
        expect(chat_interface).to_be_visible()

        # 6. User types a common question
        text_input = page.locator('input[type="text"], textarea, input[placeholder*="message"]').first
        text_input.fill("What are your hours?")

        # 7. User sends the message
        send_button = page.locator('button[aria-label*="send"], button:has-text("Send")').first
        send_button.click()

        # 8. Wait for AI response
        page.wait_for_timeout(3000)

        # 9. User sees response in chat
        messages = page.locator('.message, .chat-message, [class*="message"]')
        assert messages.count() > 0, "No messages appeared after sending"

        # Journey complete: User has successfully interacted with AI

    def test_lead_capture_journey(self, page, widget_url):
        """
        Test: Visitor provides contact info (lead capture scenario).

        User Story: As a potential customer, I want to leave my contact
        details so the business can call me back.
        """
        # 1. Open demo page and widget
        page.goto(f"{widget_url}/demo.html")
        page.locator('button.widget-trigger, button[aria-label*="call"]').first.click()
        page.wait_for_timeout(1000)

        # 2. User introduces themselves with contact info
        text_input = page.locator('input[type="text"], textarea, input[placeholder*="message"]').first
        text_input.fill("Hi, I'm Sarah. Can you call me on 0412345678?")

        send_button = page.locator('button[aria-label*="send"], button:has-text("Send")').first
        send_button.click()

        page.wait_for_timeout(3000)

        # 3. AI acknowledges and responds
        messages = page.locator('.message, .chat-message, [class*="message"]')
        assert messages.count() > 0, "Lead capture message not processed"

        # 4. User asks follow-up question
        text_input.fill("Do you service the Bondi area?")
        send_button.click()

        page.wait_for_timeout(3000)

        # 5. Conversation continues naturally
        assert messages.count() >= 2, "Follow-up message not processed"

        # Journey complete: Lead captured with contact info

    def test_booking_inquiry_journey(self, page, widget_url):
        """
        Test: User inquires about booking an appointment.

        User Story: As a customer, I want to book a service appointment
        through the chat widget.
        """
        page.goto(f"{widget_url}/demo.html")
        page.locator('button.widget-trigger, button[aria-label*="call"]').first.click()
        page.wait_for_timeout(1000)

        # User messages in sequence (natural conversation)
        conversation = [
            "I'd like to book an appointment",
            "I have a leaking tap that needs fixing",
            "How much does a leak repair cost?",
            "What's your earliest availability?"
        ]

        for message in conversation:
            text_input = page.locator('input[type="text"], textarea, input[placeholder*="message"]').first
            text_input.fill(message)

            send_button = page.locator('button[aria-label*="send"], button:has-text("Send")').first
            send_button.click()

            page.wait_for_timeout(2500)

        # Should have multiple messages in thread
        messages = page.locator('.message, .chat-message, [class*="message"]')
        assert messages.count() >= len(conversation), "Booking conversation incomplete"

    def test_multi_device_journey(self, page, mobile_page, widget_url):
        """
        Test: User starts conversation on mobile, continues on desktop.

        User Story: As a user, I want my conversation to persist
        across devices.
        """
        # Start on mobile
        mobile_page.goto(f"{widget_url}/demo.html")
        mobile_page.locator('button.widget-trigger, button[aria-label*="call"]').first.click()
        mobile_page.wait_for_timeout(1000)

        # Send first message on mobile
        text_input = mobile_page.locator('input[type="text"], textarea, input[placeholder*="message"]').first
        text_input.fill("I need a plumber")

        send_button = mobile_page.locator('button[aria-label*="send"], button:has-text("Send")').first
        send_button.click()

        mobile_page.wait_for_timeout(2000)

        # Get session ID from mobile (if exposed)
        # In real implementation, session would be stored in localStorage/cookie

        # Continue on desktop (same demo for testing)
        page.goto(f"{widget_url}/demo.html")
        page.locator('button.widget-trigger, button[aria-label*="call"]').first.click()
        page.wait_for_timeout(1000)

        # Send follow-up on desktop
        text_input = page.locator('input[type="text"], textarea, input[placeholder*="message"]').first
        text_input.fill("Can you come today?")

        send_button = page.locator('button[aria-label*="send"], button:has-text("Send")').first
        send_button.click()

        page.wait_for_timeout(2000)

        # Verify conversation continues
        messages = page.locator('.message, .chat-message, [class*="message"]')
        assert messages.count() > 0


class TestRealisticScenarios:
    """Real-world usage scenarios based on Gemini chat examples."""

    def test_after_hours_inquiry(self, page, widget_url):
        """
        Scenario: Customer calls after business hours (AI handles 24/7).

        Based on: DEMO_RECORDING_SUMMARY.md - "24/7 availability pitch"
        """
        page.goto(f"{widget_url}/demo.html")
        page.locator('button.widget-trigger, button[aria-label*="call"]').first.click()
        page.wait_for_timeout(1000)

        text_input = page.locator('input[type="text"], textarea, input[placeholder*="message"]').first
        text_input.fill("Are you open now? It's 11pm")

        send_button = page.locator('button[aria-label*="send"], button:has-text("Send")').first
        send_button.click()

        page.wait_for_timeout(3000)

        messages = page.locator('.message, .chat-message, [class*="message"]')
        assert messages.count() > 0, "After-hours message not handled"

    def test_pricing_inquiry(self, page, widget_url):
        """
        Scenario: Customer asks about pricing.

        Based on: ReceptionistAI demo scripts - pricing/quote requests
        """
        page.goto(f"{widget_url}/demo.html")
        page.locator('button.widget-trigger, button[aria-label*="call"]').first.click()
        page.wait_for_timeout(1000)

        pricing_questions = [
            "How much do you charge?",
            "What's the cost for a toilet repair?",
            "Do you have a call-out fee?"
        ]

        for question in pricing_questions:
            text_input = page.locator('input[type="text"], textarea, input[placeholder*="message"]').first
            text_input.fill(question)

            send_button = page.locator('button[aria-label*="send"], button:has-text("Send")').first
            send_button.click()

            page.wait_for_timeout(2500)

        messages = page.locator('.message, .chat-message, [class*="message"]')
        assert messages.count() >= len(pricing_questions)

    def test_service_area_inquiry(self, page, widget_url):
        """
        Scenario: Customer asks if business services their area.
        """
        page.goto(f"{widget_url}/demo.html")
        page.locator('button.widget-trigger, button[aria-label*="call"]').first.click()
        page.wait_for_timeout(1000)

        text_input = page.locator('input[type="text"], textarea, input[placeholder*="message"]').first
        text_input.fill("Do you service Bondi and Randwick?")

        send_button = page.locator('button[aria-label*="send"], button:has-text("Send")').first
        send_button.click()

        page.wait_for_timeout(3000)

        messages = page.locator('.message, .chat-message, [class*="message"]')
        assert messages.count() > 0

    def test_emergency_request(self, page, widget_url):
        """
        Scenario: Customer has an emergency (burst pipe, flood, etc).
        """
        page.goto(f"{widget_url}/demo.html")
        page.locator('button.widget-trigger, button[aria-label*="call"]').first.click()
        page.wait_for_timeout(1000)

        text_input = page.locator('input[type="text"], textarea, input[placeholder*="message"]').first
        text_input.fill("URGENT: I have a burst pipe flooding my kitchen!")

        send_button = page.locator('button[aria-label*="send"], button:has-text("Send")').first
        send_button.click()

        page.wait_for_timeout(3000)

        messages = page.locator('.message, .chat-message, [class*="message"]')
        assert messages.count() > 0, "Emergency message not handled"


class TestWidgetBehavior:
    """Test widget-specific behaviors and edge cases."""

    def test_widget_minimize_restore(self, page, widget_url):
        """
        Test: User can minimize and restore the widget.
        """
        page.goto(f"{widget_url}/demo.html")

        # Open widget
        page.locator('button.widget-trigger, button[aria-label*="call"]').first.click()
        page.wait_for_timeout(1000)

        chat_interface = page.locator('.chat-interface, .chat-window')
        expect(chat_interface).to_be_visible()

        # Look for minimize/close button
        close_button = page.locator('button[aria-label*="close"], button[aria-label*="minimize"], .close-button').first

        if close_button.is_visible():
            close_button.click()
            page.wait_for_timeout(500)

            # Widget should be hidden
            expect(chat_interface).not_to_be_visible()

            # Re-open widget
            page.locator('button.widget-trigger, button[aria-label*="call"]').first.click()
            page.wait_for_timeout(500)

            # Should be visible again
            expect(chat_interface).to_be_visible()

    def test_widget_position(self, page, widget_url):
        """
        Test: Widget appears in correct position (bottom-right corner).
        """
        page.goto(f"{widget_url}/demo.html")

        trigger = page.locator('button.widget-trigger, button[aria-label*="call"]').first

        # Get button position
        box = trigger.bounding_box()

        viewport = page.viewport_size

        # Should be in bottom-right area
        # Exact position varies, but should be near right edge and bottom
        assert box['x'] > viewport['width'] * 0.7, "Widget not positioned on right side"
        assert box['y'] > viewport['height'] * 0.5, "Widget not positioned in lower half"

    def test_conversation_scroll(self, page, widget_url):
        """
        Test: Long conversations should scroll properly.
        """
        page.goto(f"{widget_url}/demo.html")
        page.locator('button.widget-trigger, button[aria-label*="call"]').first.click()
        page.wait_for_timeout(1000)

        # Send many messages to test scrolling
        for i in range(10):
            text_input = page.locator('input[type="text"], textarea, input[placeholder*="message"]').first
            text_input.fill(f"Test message number {i+1}")

            send_button = page.locator('button[aria-label*="send"], button:has-text("Send")').first
            send_button.click()

            page.wait_for_timeout(1500)

        # Check that messages container is scrollable
        messages_container = page.locator('.messages, .chat-messages, [class*="message-container"]').first

        if messages_container.is_visible():
            scroll_height = messages_container.evaluate("el => el.scrollHeight")
            client_height = messages_container.evaluate("el => el.clientHeight")

            # If scroll_height > client_height, container is scrollable
            # This indicates proper handling of long conversations
            assert scroll_height >= client_height, "Messages container not handling overflow"
