#!/usr/bin/env python3
"""
Complete test for cashier dashboard functionality
"""

import sys
import os
import requests
import json
from pathlib import Path

# Add project root to path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

def test_server_connection():
    """Test if server is running and responding"""
    print("=== Testing Server Connection ===")

    try:
        response = requests.get("http://localhost:8080/", timeout=5, allow_redirects=False)
        if response.status_code == 302 and "login" in response.headers.get('Location', ''):
            print("✅ Server is running and responding (redirects to login)")
            return True
        elif response.status_code == 200 and "login" in response.text.lower():
            print("✅ Server is running and responding (login page loaded)")
            return True
        else:
            print(f"❌ Unexpected response: {response.status_code}")
            return False
    except requests.exceptions.RequestException as e:
        print(f"❌ Server not responding: {e}")
        return False

def test_login():
    """Test login functionality"""
    print("\n=== Testing Login ===")

    try:
        # Test login with cashier credentials
        login_data = {
            'username': 'cashier',
            'password': 'cashier'
        }

        session = requests.Session()
        response = session.post("http://localhost:8080/auth/login", data=login_data, timeout=10)

        if response.status_code == 302:
            print("✅ Login successful")
            return session
        else:
            print(f"❌ Login failed: {response.status_code}")
            return None
    except Exception as e:
        print(f"❌ Login error: {e}")
        return None

def test_api_endpoint(session):
    """Test the cashier pending matches API endpoint"""
    print("\n=== Testing API Endpoint ===")

    try:
        response = session.get("http://localhost:8080/api/cashier/pending-matches", timeout=10)

        if response.status_code == 200:
            data = response.json()
            print("✅ API endpoint responding")
            print(f"   Response: {json.dumps(data, indent=2)}")

            if data.get('success'):
                print(f"   Total matches: {data.get('total', 0)}")
                if data.get('matches'):
                    print("   Sample matches:")
                    for i, match in enumerate(data['matches'][:2]):
                        print(f"     {i+1}. {match.get('fighter1_township', 'N/A')} vs {match.get('fighter2_township', 'N/A')}")
                return True
            else:
                print(f"   API returned error: {data.get('error', 'Unknown error')}")
                return False
        else:
            print(f"❌ API endpoint failed: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ API error: {e}")
        return False

def test_dashboard_access(session):
    """Test accessing the cashier dashboard"""
    print("\n=== Testing Dashboard Access ===")

    try:
        response = session.get("http://localhost:8080/cashier", timeout=10)

        if response.status_code == 200:
            print("✅ Dashboard accessible")

            # Check if the page contains expected elements
            content = response.text
            if "Cashier Dashboard" in content:
                print("   Contains dashboard title")
            if "pending-matches-container" in content:
                print("   Contains pending matches container")
            if "loadPendingMatches" in content:
                print("   Contains JavaScript function")
            else:
                print("   ⚠️  JavaScript function not found in HTML")

            return True
        else:
            print(f"❌ Dashboard access failed: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ Dashboard error: {e}")
        return False

def main():
    """Run all tests"""
    print("Cashier Dashboard Complete Test")
    print("=" * 40)

    # Test 1: Server connection
    if not test_server_connection():
        print("\n❌ Server is not running. Please start the server first:")
        print("   python main.py --web-port 8080 --screen-cast-port 8081 --no-qt")
        return

    # Test 2: Login
    session = test_login()
    if not session:
        print("\n❌ Cannot proceed without successful login")
        return

    # Test 3: API endpoint
    api_success = test_api_endpoint(session)

    # Test 4: Dashboard access
    dashboard_success = test_dashboard_access(session)

    # Summary
    print("\n" + "=" * 40)
    print("SUMMARY:")
    print(f"Server Connection: ✅")
    print(f"Login: ✅")
    print(f"API Endpoint: {'✅' if api_success else '❌'}")
    print(f"Dashboard Access: {'✅' if dashboard_success else '❌'}")

    if api_success and dashboard_success:
        print("\n🎉 All tests passed! The cashier dashboard should be working.")
        print("\nTo access the dashboard:")
        print("1. Open browser to: http://localhost:8080/cashier")
        print("2. Login with: cashier / cashier")
        print("3. The pending matches should load automatically")
    else:
        print("\n❌ Some tests failed. Check the output above for details.")

if __name__ == "__main__":
    main()