"""Test GCP authentication with RegistryClient.

This test verifies that the GCP authentication integration works correctly.
Run this test in an environment with GCP credentials (e.g., Vertex AI Workbench).
"""

import sys
import os

# Add mca_sdk to path if running from mca-prototype directory
sys.path.insert(0, os.path.dirname(__file__))

from mca_sdk.registry.client import (
    RegistryClient,
    GCP_TOKEN_LIFETIME_SECS,
    GCP_TOKEN_REFRESH_MARGIN_SECS,
)


def test_constants_exist():
    """Test that GCP token constants are defined."""
    print("Testing GCP token constants...")
    assert GCP_TOKEN_LIFETIME_SECS == 3600, f"Expected 3600, got {GCP_TOKEN_LIFETIME_SECS}"
    assert (
        GCP_TOKEN_REFRESH_MARGIN_SECS == 300
    ), f"Expected 300, got {GCP_TOKEN_REFRESH_MARGIN_SECS}"
    print("[OK] Constants defined correctly")


def test_gcp_auth_initialization():
    """Test that RegistryClient can be initialized with GCP auth."""
    print("\nTesting GCP auth initialization...")

    # Test with GCP auth disabled (should work without google-auth)
    client = RegistryClient(url="https://example.com", use_gcp_auth=False)
    assert not client._use_gcp_auth
    print("[OK] Client initialized without GCP auth")
    client.close()

    # Test that token and use_gcp_auth are mutually exclusive
    try:
        client = RegistryClient(url="https://example.com", token="test-token", use_gcp_auth=True)
        print("[FAIL] Should have raised error for both token and use_gcp_auth")
        sys.exit(1)
    except Exception as e:
        if "Cannot use both token and use_gcp_auth" in str(e):
            print("[OK] Correctly rejects both token and use_gcp_auth")
        else:
            print(f"[FAIL] Unexpected error: {e}")
            sys.exit(1)


def test_gcp_auth_with_real_credentials():
    """Test GCP auth with real credentials (requires GCP environment)."""
    print("\nTesting GCP auth with real credentials...")

    # This will only work in a GCP environment with ADC configured
    registry_url = "https://emms-registration-api-dev-rlaptra7zq-ue.a.run.app"

    try:
        client = RegistryClient(
            url=registry_url,
            use_gcp_auth=True,
            cache_ttl_secs=300,
            refresh_interval_secs=0,  # Disable config refresh for this test
        )
    except Exception as e:
        from mca_sdk.utils.exceptions import RegistryAuthError

        if isinstance(
            e, RegistryAuthError
        ) and "Neither metadata server or valid service account credentials" in str(e):
            print("[WARN] Skipping - No GCP credentials available")
            print("  This test requires GCP Application Default Credentials (ADC)")
            print(
                "  Run in GCP environment (e.g., Vertex AI Workbench) or set GOOGLE_APPLICATION_CREDENTIALS"
            )
            return
        else:
            raise

    try:
        print("[OK] Client initialized with GCP auth")
        print(f"  Token expiry: {client._gcp_token_expiry}")
        print(f"  Token exists: {client._gcp_token is not None}")

        # Try to fetch a config (this will test the actual authentication)
        try:
            # This endpoint should exist based on the user's test
            # We're not testing the response, just that auth works
            print("\n  Attempting authenticated request...")
            # Note: This will fail if the model doesn't exist, but that's OK
            # We're just testing that the auth header is set correctly
            import requests

            response = requests.get(
                f"{registry_url}/api/v1/configs",
                headers=client._session.headers,
                timeout=5.0,
            )
            print(f"  Response status: {response.status_code}")
            if response.status_code == 200:
                data = response.json()
                print(f"  [OK] Authenticated successfully - {data.get('total', 0)} configs found")
            elif response.status_code in (401, 403):
                print(f"  [FAIL] Authentication failed: {response.status_code}")
            else:
                print(f"  Response: {response.status_code}")

        except Exception as e:
            print(f"  Request error: {e}")

        client.close()
        print("[OK] Client closed successfully")

    except ValueError as e:
        if "google-auth library not available" in str(e):
            print("[WARN] Skipping - google-auth not installed")
            print("  Install with: pip install google-auth")
        else:
            raise


if __name__ == "__main__":
    print("=" * 60)
    print("GCP Registry Authentication Test")
    print("=" * 60)

    test_constants_exist()
    test_gcp_auth_initialization()
    test_gcp_auth_with_real_credentials()

    print("\n" + "=" * 60)
    print("All tests passed!")
    print("=" * 60)
