"""Comprehensive integration test for SDK-Registry API integration.

This test verifies that the SDK correctly integrates with the Registry API
following the specifications in GET_EndpointsDoc.md.

Requirements:
- GCP environment with Application Default Credentials (ADC)
- Access to registry API at https://emms-registration-api-dev-rlaptra7zq-ue.a.run.app
"""

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
from mca_sdk.registry.models import ModelConfig
from mca_sdk.utils.exceptions import (
    RegistryAuthError,
    RegistryConfigNotFoundError,
    RegistryConnectionError,
)


def test_gcp_authentication():
    """Test GCP ID token authentication."""
    print("\n[TEST 1] GCP Authentication")
    print("-" * 60)

    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 background refresh for testing
        )

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

        client.close()
        return True

    except RegistryAuthError as e:
        if "Neither metadata server or valid service account credentials" in str(e):
            print("[SKIP] No GCP credentials available")
            print("  Run in GCP environment or set GOOGLE_APPLICATION_CREDENTIALS")
            return None  # Skip, not a failure
        else:
            print(f"[FAIL] Authentication error: {e}")
            return False
    except Exception as e:
        print(f"[FAIL] Unexpected error: {e}")
        import traceback

        traceback.print_exc()
        return False


def test_list_all_configs():
    """Test GET /api/v1/configs - List all configurations."""
    print("\n[TEST 2] List All Configs")
    print("-" * 60)

    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,
        )

        # Make direct request to /api/v1/configs
        import requests

        response = requests.get(
            f"{registry_url}/api/v1/configs",
            headers=client._session.headers,
            timeout=5.0,
        )

        if response.status_code == 200:
            data = response.json()
            print(f"[OK] Retrieved {data.get('total', 0)} configs")
            print(f"  Returned: {len(data.get('items', []))} items")

            # Show first config structure
            if data.get("items"):
                first_config = data["items"][0]
                print("\n  Sample config structure:")
                print(f"    model_id: {first_config.get('model_id')}")
                print(f"    service_name: {first_config.get('service_name')}")
                print(f"    team_name: {first_config.get('team_name')}")
                print(f"    model_category: {first_config.get('model_category')}")
                print(f"    model_type: {first_config.get('model_type')}")
                print(f"    has config: {'config' in first_config}")
                print(f"    has thresholds: {'thresholds' in first_config}")

            client.close()
            return True
        else:
            print(f"[FAIL] Status {response.status_code}: {response.text}")
            client.close()
            return False

    except RegistryAuthError as e:
        if "Neither metadata server or valid service account credentials" in str(e):
            print("[SKIP] No GCP credentials")
            return None
        print(f"[FAIL] Auth error: {e}")
        return False
    except Exception as e:
        print(f"[FAIL] Error: {e}")
        import traceback

        traceback.print_exc()
        return False


def test_fetch_model_config_by_id():
    """Test GET /api/v1/configs/{model_id} - Fetch specific model config."""
    print("\n[TEST 3] Fetch Model Config by ID")
    print("-" * 60)

    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,
        )

        # First, get list of configs to find a valid model_id
        import requests

        response = requests.get(
            f"{registry_url}/api/v1/configs?limit=1",
            headers=client._session.headers,
            timeout=5.0,
        )

        if response.status_code != 200:
            print(f"[FAIL] Could not list configs: {response.status_code}")
            client.close()
            return False

        data = response.json()
        if not data.get("items"):
            print("[SKIP] No configs available to test")
            client.close()
            return None

        model_id = data["items"][0]["model_id"]
        print(f"  Testing with model_id: {model_id}")

        # Now fetch using SDK's fetch_model_config method
        try:
            config = client.fetch_model_config(model_id)

            print("[OK] Fetched config successfully")
            print(f"  service_name: {config.service_name}")
            print(f"  model_id: {config.model_id}")
            print(f"  model_version: {config.model_version}")
            print(f"  team_name: {config.team_name}")
            print(f"  model_category: {config.model_category}")
            print(f"  model_type: {config.model_type}")
            print(f"  thresholds: {config.thresholds}")
            print(f"  extra_resource: {config.extra_resource}")

            # Validate it's a ModelConfig instance
            assert isinstance(config, ModelConfig), "Should return ModelConfig instance"
            assert config.model_id == model_id, "model_id should match"

            client.close()
            return True

        except RegistryConfigNotFoundError:
            print(f"[FAIL] Model {model_id} not found (404)")
            client.close()
            return False
        except Exception as e:
            print(f"[FAIL] Error fetching config: {e}")
            import traceback

            traceback.print_exc()
            client.close()
            return False

    except RegistryAuthError as e:
        if "Neither metadata server or valid service account credentials" in str(e):
            print("[SKIP] No GCP credentials")
            return None
        print(f"[FAIL] Auth error: {e}")
        return False
    except Exception as e:
        print(f"[FAIL] Error: {e}")
        import traceback

        traceback.print_exc()
        return False


def test_cache_behavior():
    """Test that caching works correctly."""
    print("\n[TEST 4] Cache Behavior")
    print("-" * 60)

    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,
        )

        # Get a model_id
        import requests

        response = requests.get(
            f"{registry_url}/api/v1/configs?limit=1",
            headers=client._session.headers,
            timeout=5.0,
        )

        if response.status_code != 200 or not response.json().get("items"):
            print("[SKIP] No configs available")
            client.close()
            return None

        model_id = response.json()["items"][0]["model_id"]

        # First fetch - should hit API
        config1 = client.fetch_model_config(model_id)
        print("[OK] First fetch completed")

        # Second fetch - should hit cache
        config2 = client.fetch_model_config(model_id)
        print("[OK] Second fetch completed (from cache)")

        # Verify they're the same
        assert config1.model_id == config2.model_id
        assert config1.service_name == config2.service_name

        # Clear cache and fetch again
        client.clear_cache()
        config3 = client.fetch_model_config(model_id)
        print("[OK] Third fetch after cache clear")

        assert config3.model_id == config1.model_id

        client.close()
        return True

    except RegistryAuthError as e:
        if "Neither metadata server or valid service account credentials" in str(e):
            print("[SKIP] No GCP credentials")
            return None
        print(f"[FAIL] Auth error: {e}")
        return False
    except Exception as e:
        print(f"[FAIL] Error: {e}")
        import traceback

        traceback.print_exc()
        return False


def test_error_handling():
    """Test error handling for non-existent model."""
    print("\n[TEST 5] Error Handling (404)")
    print("-" * 60)

    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,
        )

        # Try to fetch non-existent model
        fake_model_id = "00000000-0000-0000-0000-000000000000"

        try:
            config = client.fetch_model_config(fake_model_id)
            print("[FAIL] Should have raised RegistryConfigNotFoundError")
            client.close()
            return False
        except RegistryConfigNotFoundError as e:
            print("[OK] Correctly raised RegistryConfigNotFoundError")
            print(f"  Message: {e}")
            client.close()
            return True

    except RegistryAuthError as e:
        if "Neither metadata server or valid service account credentials" in str(e):
            print("[SKIP] No GCP credentials")
            return None
        print(f"[FAIL] Auth error: {e}")
        return False
    except Exception as e:
        print(f"[FAIL] Unexpected error: {e}")
        import traceback

        traceback.print_exc()
        return False


def main():
    """Run all integration tests."""
    print("=" * 60)
    print("SDK-Registry API Integration Tests")
    print("=" * 60)

    tests = [
        test_gcp_authentication,
        test_list_all_configs,
        test_fetch_model_config_by_id,
        test_cache_behavior,
        test_error_handling,
    ]

    results = []
    for test in tests:
        result = test()
        results.append(result)

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

    passed = sum(1 for r in results if r is True)
    failed = sum(1 for r in results if r is False)
    skipped = sum(1 for r in results if r is None)

    print(f"Passed:  {passed}/{len(tests)}")
    print(f"Failed:  {failed}/{len(tests)}")
    print(f"Skipped: {skipped}/{len(tests)}")

    if failed > 0:
        print("\n[FAIL] Some tests failed")
        sys.exit(1)
    elif skipped == len(tests):
        print("\n[SKIP] All tests skipped (no GCP credentials)")
        sys.exit(0)
    else:
        print("\n[OK] All tests passed!")
        sys.exit(0)


if __name__ == "__main__":
    main()
