#!/usr/bin/env python3
"""
Test script to check API endpoints for debugging fixtures overlay
"""

import requests
import json
import sys
from pathlib import Path

def test_fixtures_api():
    """Test the fixtures API endpoint"""
    print("Testing fixtures API endpoint...")

    # Try different possible URLs
    urls_to_test = [
        "http://127.0.0.1:5001/api/fixtures",
        "http://localhost:5001/api/fixtures",
        "http://127.0.0.1:5000/api/fixtures",
        "http://localhost:5000/api/fixtures"
    ]

    for url in urls_to_test:
        print(f"\nTrying URL: {url}")
        try:
            response = requests.get(url, timeout=5)
            print(f"Status Code: {response.status_code}")

            if response.status_code == 200:
                try:
                    data = response.json()
                    print("Response data:")
                    print(json.dumps(data, indent=2))

                    if 'success' in data and data['success']:
                        print(f"✅ SUCCESS: Found {data.get('total', 0)} fixtures")
                        return True
                    else:
                        print("❌ API returned success=false")
                        return False

                except json.JSONDecodeError as e:
                    print(f"❌ Invalid JSON response: {e}")
                    print(f"Raw response: {response.text[:500]}...")
                    return False
            else:
                print(f"❌ HTTP Error: {response.status_code}")
                print(f"Response: {response.text[:200]}...")

        except requests.exceptions.ConnectionError:
            print("❌ Connection refused - server not running")
        except requests.exceptions.Timeout:
            print("❌ Request timed out")
        except Exception as e:
            print(f"❌ Error: {e}")

    print("\n❌ All URLs failed - API server may not be running")
    return False

def test_web_dashboard_status():
    """Test if web dashboard is running"""
    print("\nTesting web dashboard status...")

    urls_to_test = [
        "http://127.0.0.1:5001/",
        "http://localhost:5001/",
        "http://127.0.0.1:5000/",
        "http://localhost:5000/"
    ]

    for url in urls_to_test:
        print(f"Trying URL: {url}")
        try:
            response = requests.get(url, timeout=5)
            print(f"Status Code: {response.status_code}")
            if response.status_code == 200:
                print("✅ Web dashboard is running")
                return True
        except Exception as e:
            print(f"❌ Error: {e}")

    print("❌ Web dashboard not accessible")
    return False

def main():
    print("=== MbetterClient API Test ===")

    # Test web dashboard first
    web_running = test_web_dashboard_status()

    if not web_running:
        print("\n⚠️  Web dashboard is not running. Make sure to start the web server first.")
        print("Run: python main.py --web-only")
        sys.exit(1)

    # Test fixtures API
    api_working = test_fixtures_api()

    if api_working:
        print("\n✅ API test completed successfully")
    else:
        print("\n❌ API test failed")
        print("\nTroubleshooting tips:")
        print("1. Make sure the web server is running")
        print("2. Check if the database has fixture data")
        print("3. Check the web server logs for errors")
        print("4. Verify the fixtures endpoint is properly configured")

if __name__ == "__main__":
    main()