#!/usr/bin/env python3
"""
FastAPI Route Diagnostics Script

Run this script to check if your store routes are properly configured.
Usage: python route_diagnostics.py
"""


def check_route_order():
    """Check if routes are registered in the correct order."""
    print("🔍 Checking FastAPI Route Configuration...\n")

    try:
        # Try to import the store router
        from app.api.v1.store import router as store_router

        print("✅ Successfully imported store router\n")

        # Check if routes are registered
        routes = store_router.routes
        print(f"📊 Total routes registered: {len(routes)}\n")

        # Analyze route order
        json_routes = []
        html_routes = []

        for route in routes:
            if hasattr(route, "path"):
                path = route.path
                methods = getattr(route, "methods", set())

                # Determine if JSON or HTML based on common patterns
                if "login" in path or "dashboard" in path or "products" in path:
                    # Check response class if available
                    if hasattr(route, "response_class"):
                        response_class = str(route.response_class)
                        if "HTML" in response_class:
                            html_routes.append((path, methods))
                        else:
                            json_routes.append((path, methods))
                    else:
                        # Check endpoint name/tags
                        endpoint = getattr(route, "endpoint", None)
                        if endpoint and "page" in endpoint.__name__.lower():
                            html_routes.append((path, methods))
                        else:
                            json_routes.append((path, methods))

        print("📋 Route Analysis:")
        print(f"   JSON API routes: {len(json_routes)}")
        print(f"   HTML page routes: {len(html_routes)}\n")

        # Check for specific store info route
        store_info_found = False
        for route in routes:
            if hasattr(route, "path"):
                if route.path == "/{store_code}" and "GET" in getattr(
                    route, "methods", set()
                ):
                    store_info_found = True
                    print("✅ Found store info endpoint: GET /{store_code}")
                    break

        if not store_info_found:
            print("❌ WARNING: Store info endpoint (GET /{store_code}) not found!")
            print("   This is likely causing your JSON parsing error.")
            print("   Action required: Add the store info endpoint\n")
            return False

        print("\n✅ Route configuration looks good!")
        return True

    except ImportError as e:
        print(f"❌ Error importing store router: {e}")
        print("   Make sure you're running this from your project root")
        return False
    except Exception as e:
        print(f"❌ Unexpected error: {e}")
        return False


def test_store_endpoint():
    """Test if the store endpoint returns JSON."""
    print("\n🧪 Testing Store Endpoint...\n")

    try:
        import requests

        # Test with a sample store code
        store_code = "ORION"
        url = f"http://localhost:8000/api/v1/store/{store_code}"

        print(f"📡 Making request to: {url}")

        response = requests.get(url, timeout=5)

        print(f"   Status Code: {response.status_code}")
        print(f"   Content-Type: {response.headers.get('content-type', 'N/A')}")

        # Check if response is JSON
        content_type = response.headers.get("content-type", "")
        if "application/json" in content_type:
            print("✅ Response is JSON")
            data = response.json()
            print(f"   Store: {data.get('name', 'N/A')}")
            print(f"   Code: {data.get('store_code', 'N/A')}")
            return True
        if "text/html" in content_type:
            print("❌ ERROR: Response is HTML, not JSON!")
            print("   This confirms the route ordering issue")
            print("   The HTML page route is catching the API request")
            return False
        print(f"⚠️  Unknown content type: {content_type}")
        return False

    except requests.exceptions.ConnectionError:
        print("⚠️  Cannot connect to server. Is FastAPI running on localhost:8000?")
        return None
    except Exception as e:
        print(f"❌ Error testing endpoint: {e}")
        return False


def main():
    """Run all diagnostics."""
    print("=" * 60)
    print("FastAPI Store Route Diagnostics")
    print("=" * 60 + "\n")

    # Check route configuration
    config_ok = check_route_order()

    # Test actual endpoint
    endpoint_ok = test_store_endpoint()

    # Summary
    print("\n" + "=" * 60)
    print("SUMMARY")
    print("=" * 60)

    if config_ok and endpoint_ok:
        print("✅ All checks passed! Your store routes are configured correctly.")
    elif config_ok is False:
        print("❌ Route configuration issues detected.")
        print("   Action: Add store info endpoint and check route order")
    elif endpoint_ok is False:
        print("❌ Endpoint is returning HTML instead of JSON.")
        print("   Action: Check route registration order in store/__init__.py")
    elif endpoint_ok is None:
        print("⚠️  Could not test endpoint (server not running)")
        print("   Action: Start your FastAPI server and run this script again")

    print("\n📚 See TROUBLESHOOTING_GUIDE.md for detailed solutions")


if __name__ == "__main__":
    main()
