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

import requests
import json

def test_server():
    """Test if server is responding"""
    print("=== Testing Server Connection ===")

    try:
        response = requests.get("http://localhost:8080/", timeout=5, allow_redirects=False)
        if response.status_code == 302:
            print("OK Server is running and responding (redirects to login)")
            return True
        else:
            print(f"ERROR Unexpected response: {response.status_code}")
            return False
    except Exception as e:
        print(f"ERROR Server not responding: {e}")
        return False

def test_login():
    """Test login with cashier credentials"""
    print("\n=== Testing Login ===")

    try:
        session = requests.Session()

        # First get the login page to get CSRF token if needed
        login_page = session.get("http://localhost:8080/auth/login", timeout=10)
        print(f"Login page status: {login_page.status_code}")

        # Try login
        login_data = {
            'username': 'cashier',
            'password': 'cashier123'
        }

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

        print(f"Login response status: {response.status_code}")
        print(f"Login response location: {response.headers.get('Location', 'N/A')}")

        if response.status_code == 302 and 'cashier' in response.headers.get('Location', ''):
            print("OK Login successful")
            return session
        else:
            print("ERROR Login failed")
            return None

    except Exception as e:
        print(f"ERROR Login error: {e}")
        return None

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

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

        print(f"API response status: {response.status_code}")

        if response.status_code == 200:
            data = response.json()
            print("OK 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"ERROR API endpoint failed: {response.status_code}")
            print(f"Response: {response.text[:200]}...")
            return False

    except Exception as e:
        print(f"ERROR API error: {e}")
        return False

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

    # Test 1: Server connection
    if not test_server():
        print("\nERROR 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("\nERROR Cannot proceed without successful login")
        return

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

    # Summary
    print("\n" + "=" * 40)
    print("SUMMARY:")
    print(f"Server Connection: OK")
    print(f"Login: OK")
    print(f"API Endpoint: {'OK' if api_success else 'ERROR'}")

    if api_success:
        print("\nSUCCESS The cashier dashboard API is working!")
        print("If the web interface is not showing matches, the issue is likely in the JavaScript.")
    else:
        print("\nERROR The API is not working. Check server logs for errors.")

if __name__ == "__main__":
    main()