#!/usr/bin/env python3
"""
Test Billing Tools
"""

import sys
import os
from dotenv import load_dotenv

# Add src to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

# Set dummy environment variables for testing
os.environ['BILLING_DB_1_HOST'] = 'localhost'
os.environ['BILLING_DB_1_USER'] = 'test'
os.environ['BILLING_DB_1_PASS'] = 'test'
os.environ['BILLING_DB_1_NAME'] = 'testdb'

# Also test legacy format
os.environ['BILLING_DB_HOST'] = 'legacyhost'
os.environ['BILLING_DB_USER'] = 'legacyuser'
os.environ['BILLING_DB_PASS'] = 'legacypass'
os.environ['BILLING_DB_NAME'] = 'legacydb'

from src.vultr_mcp.billing import BillingDatabase

def test_billing_module():
    print("Testing BillingDatabase module...")
    
    try:
        # Create instance
        billing = BillingDatabase()
        
        # Test server loading
        servers = billing.list_servers()
        print(f"Loaded servers: {len(servers)}")
        for server in servers:
            print(f"  Server {server['server_id']}: {server['host']} ({server['database']})")
        
        # Test get_server_config
        config1 = billing.get_server_config('1')
        print(f"\nServer 1 config: {config1['host'] if config1 else 'None'}")
        
        # Test server 2 (should not exist)
        config2 = billing.get_server_config('2')
        print(f"Server 2 config: {'Exists' if config2 else 'None'}")
        
        # Test check_connection (will fail but should handle gracefully)
        print("\nTesting connection check (will fail due to dummy credentials):")
        result = billing.check_connection('1')
        print(f"Success: {result.get('success', False)}")
        if not result.get('success'):
            print(f"Error: {result.get('error', 'Unknown')}")
            if result.get('hint'):
                print(f"Hint: {result['hint']}")
        
        # Test search customers (should fail gracefully)
        print("\nTesting search customers (will fail):")
        search_result = billing.search_customers('test', '1', 5, 0)
        print(f"Success: {search_result.get('success', False)}")
        
        # Test normalize phone number
        print("\nTesting phone normalization:")
        test_numbers = ['62812345678', '0812345678', '62812345678@c.us']
        for num in test_numbers:
            normalized = billing._normalize_phone_number(num)
            print(f"  {num} -> {normalized}")
        
        print("\n✅ Billing module tests completed (expected failures due to dummy credentials)")
        return True
        
    except Exception as e:
        print(f"❌ Error testing billing module: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == '__main__':
    success = test_billing_module()
    sys.exit(0 if success else 1)