#!/usr/bin/env python3
"""
SDK Validation Script

Tests the Python SDK against the live API to verify response structures match.
Run with: python validate_sdk.py <api_key> [phone_number]
"""

import sys
import json
from typing import Any, Dict

# Add the SDK to path for testing
sys.path.insert(0, '.')

from verirouteintel import (
    VeriRoute,
    VRI,
    CnamResult,
    LrnResult,
    TrustResult,
    SpamResult,
    MessagingResult,
    VeriRouteError,
    AuthenticationError,
    InvalidPhoneError,
)


def print_result(name: str, success: bool, details: str = ""):
    status = "\033[92mPASS\033[0m" if success else "\033[91mFAIL\033[0m"
    print(f"  [{status}] {name}")
    if details:
        print(f"         {details}")


def validate_cnam(vri: VeriRoute, phone: str) -> bool:
    """Validate CNAM endpoint response structure."""
    print("\n=== CNAM Validation ===")

    try:
        # Basic CNAM
        result = vri.cnam(phone)

        # Check it's the right type
        print_result("Returns CnamResult", isinstance(result, CnamResult))

        # Check required fields exist
        print_result("Has 'number' field", hasattr(result, 'number') and result.number is not None)
        print_result("Has 'cnam' field", hasattr(result, 'cnam'))

        print(f"         Response: number={result.number}, cnam={result.cnam}")

        # With spam
        result_spam = vri.cnam(phone, include_spam=True)
        print_result("With include_spam=True", hasattr(result_spam, 'spam_type'))
        print(f"         spam_type={result_spam.spam_type}")

        return True
    except VeriRouteError as e:
        print_result("CNAM request", False, f"Error: {e}")
        return False


def validate_lrn(vri: VeriRoute, phone: str) -> bool:
    """Validate LRN endpoint response structure."""
    print("\n=== LRN Validation ===")

    try:
        # Basic LRN
        result = vri.lrn(phone)

        print_result("Returns LrnResult", isinstance(result, LrnResult))
        print_result("Has 'phone_number' field", hasattr(result, 'phone_number'))
        print_result("Has 'lrn' field", hasattr(result, 'lrn'))
        print_result("Has 'carrier' field", hasattr(result, 'carrier'))
        print_result("Has 'line_type' field", hasattr(result, 'line_type'))

        print(f"         Response: lrn={result.lrn}, carrier={result.carrier}, line_type={result.line_type}")

        # With enhanced data
        result_enhanced = vri.lrn(phone, include_enhanced=True)
        has_enhanced = result_enhanced.enhanced is not None
        print_result("With include_enhanced=True returns enhanced data", has_enhanced)

        if has_enhanced:
            e = result_enhanced.enhanced
            print_result("Enhanced has 'city'", hasattr(e, 'city'))
            print_result("Enhanced has 'state'", hasattr(e, 'state'))
            print_result("Enhanced has 'timezone'", hasattr(e, 'timezone'))
            print(f"         Enhanced: city={e.city}, state={e.state}, timezone={e.timezone}")

        # With messaging
        result_msg = vri.lrn(phone, messaging_lookup=True)
        has_messaging = result_msg.messaging is not None
        print_result("With messaging_lookup=True returns messaging data", has_messaging)

        if has_messaging:
            m = result_msg.messaging
            print_result("Messaging has 'provider'", hasattr(m, 'provider'))
            print_result("Messaging has 'enabled'", hasattr(m, 'enabled'))
            print(f"         Messaging: provider={m.provider}, enabled={m.enabled}")

        return True
    except VeriRouteError as e:
        print_result("LRN request", False, f"Error: {e}")
        return False


def validate_trust(vri: VeriRoute, phone: str) -> bool:
    """Validate Trust endpoint response structure."""
    print("\n=== Trust Validation ===")

    try:
        result = vri.trust(phone)

        print_result("Returns TrustResult", isinstance(result, TrustResult))
        print_result("Has 'number' field", hasattr(result, 'number'))
        print_result("Has 'is_spam' field", hasattr(result, 'is_spam'))
        print_result("Has 'is_robocall' field", hasattr(result, 'is_robocall'))
        print_result("Has 'is_scam' field", hasattr(result, 'is_scam'))
        print_result("Has 'spam_type' field", hasattr(result, 'spam_type'))
        print_result("Has 'complaint_count' field", hasattr(result, 'complaint_count'))

        print(f"         Response: is_spam={result.is_spam}, spam_type={result.spam_type}, complaints={result.complaint_count}")

        return True
    except VeriRouteError as e:
        print_result("Trust request", False, f"Error: {e}")
        return False


def validate_spam(vri: VeriRoute, phone: str) -> bool:
    """Validate Spam endpoint response structure."""
    print("\n=== Spam Validation ===")

    try:
        result = vri.spam(phone)

        print_result("Returns SpamResult", isinstance(result, SpamResult))
        print_result("Has 'phone_number' field", hasattr(result, 'phone_number'))
        print_result("Has 'is_spam' field", hasattr(result, 'is_spam'))
        print_result("Has 'spam_type' field", hasattr(result, 'spam_type'))
        print_result("Has 'cached' field", hasattr(result, 'cached'))
        print_result("Has 'source' field", hasattr(result, 'source'))

        print(f"         Response: is_spam={result.is_spam}, spam_type={result.spam_type}")

        return True
    except VeriRouteError as e:
        print_result("Spam request", False, f"Error: {e}")
        return False


def validate_messaging(vri: VeriRoute, phone: str) -> bool:
    """Validate Messaging endpoint response structure."""
    print("\n=== Messaging Validation ===")

    try:
        result = vri.messaging(phone)

        print_result("Returns MessagingResult", isinstance(result, MessagingResult))
        print_result("Has 'phone_number' field", hasattr(result, 'phone_number'))
        print_result("Has 'messaging_provider' field", hasattr(result, 'messaging_provider'))
        print_result("Has 'messaging_enabled' field", hasattr(result, 'messaging_enabled'))
        print_result("Has 'messaging_country' field", hasattr(result, 'messaging_country'))

        print(f"         Response: provider={result.messaging_provider}, enabled={result.messaging_enabled}")

        return True
    except VeriRouteError as e:
        print_result("Messaging request", False, f"Error: {e}")
        return False


def validate_key(vri: VeriRoute) -> bool:
    """Validate API key validation endpoint."""
    print("\n=== API Key Validation ===")

    try:
        is_valid = vri.validate_key()
        print_result("validate_key() returns bool", isinstance(is_valid, bool))
        print_result("API key is valid", is_valid)
        return is_valid
    except VeriRouteError as e:
        print_result("validate_key request", False, f"Error: {e}")
        return False


def validate_error_handling(vri: VeriRoute) -> bool:
    """Validate error handling."""
    print("\n=== Error Handling Validation ===")

    # Test invalid phone number
    try:
        vri.cnam("invalid")
        print_result("InvalidPhoneError raised for bad number", False)
    except InvalidPhoneError:
        print_result("InvalidPhoneError raised for bad number", True)
    except VeriRouteError as e:
        print_result("InvalidPhoneError raised for bad number", False, f"Got {type(e).__name__}: {e}")

    # Test invalid API key
    try:
        bad_vri = VeriRoute("invalid_key_12345")
        bad_vri.cnam("+15551234567")
        print_result("AuthenticationError raised for bad key", False)
    except AuthenticationError:
        print_result("AuthenticationError raised for bad key", True)
    except VeriRouteError as e:
        print_result("AuthenticationError raised for bad key", False, f"Got {type(e).__name__}: {e}")

    return True


def validate_vri_alias():
    """Validate VRI is an alias for VeriRoute."""
    print("\n=== VRI Alias Validation ===")
    print_result("VRI is VeriRoute", VRI is VeriRoute)
    return VRI is VeriRoute


def main():
    if len(sys.argv) < 2:
        print("Usage: python validate_sdk.py <api_key> [phone_number] [base_url]")
        print("Example: python validate_sdk.py vri_abc123 +15551234567")
        print("Example: python validate_sdk.py vri_abc123 +15551234567 http://localhost:5000")
        sys.exit(1)

    api_key = sys.argv[1]
    phone = sys.argv[2] if len(sys.argv) > 2 else "+12029001234"  # Default test number
    base_url = sys.argv[3] if len(sys.argv) > 3 else None

    print("=" * 60)
    print("VeriRoute Intel Python SDK Validation")
    print("=" * 60)
    print(f"API Base: {base_url or 'https://api-service.verirouteintel.io'}")
    print(f"Test Phone: {phone}")

    # Validate alias first (no API call needed)
    validate_vri_alias()

    # Create client
    if base_url:
        vri = VeriRoute(api_key, base_url=base_url)
    else:
        vri = VeriRoute(api_key)

    # Validate API key first
    if not validate_key(vri):
        print("\n\033[91mAPI key validation failed. Check your key.\033[0m")
        sys.exit(1)

    # Run all validations
    results = []
    results.append(("CNAM", validate_cnam(vri, phone)))
    results.append(("LRN", validate_lrn(vri, phone)))
    results.append(("Trust", validate_trust(vri, phone)))
    results.append(("Spam", validate_spam(vri, phone)))
    results.append(("Messaging", validate_messaging(vri, phone)))
    results.append(("Error Handling", validate_error_handling(vri)))

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

    passed = sum(1 for _, success in results if success)
    total = len(results)

    for name, success in results:
        status = "\033[92mPASS\033[0m" if success else "\033[91mFAIL\033[0m"
        print(f"  {name}: {status}")

    print(f"\nTotal: {passed}/{total} passed")

    if passed == total:
        print("\n\033[92mAll validations passed!\033[0m")
    else:
        print("\n\033[91mSome validations failed. Review output above.\033[0m")
        sys.exit(1)


if __name__ == "__main__":
    main()
