import sys
import os
import hmac
import hashlib
import time

# Add the backend and sdk to path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../backend')))
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../voniai')))

from voniai.signer import VoniSigner

def test_signature_parity():
    """
    Test that the SDK's signature generation matches the logic in the backend middleware.
    """
    api_key = "voni_test_key_12345"
    timestamp = int(time.time())
    method = "POST"
    path = "/api/v1/widget/proj_123/chat"
    body = '{"message": "Hello Voni"}'
    
    # 1. Generate signature using SDK Signer
    sdk_signature = VoniSigner.sign_request(
        api_key=api_key,
        method=method,
        path=path,
        body=body,
        timestamp=timestamp
    )
    
    # 2. Replicate backend middleware verification logic
    # (Extracted from app/middleware/api_key.py)
    message_to_verify = f"{timestamp}{method}{path}{body}"
    expected_signature = hmac.new(
        api_key.encode(),
        message_to_verify.encode(),
        hashlib.sha256
    ).hexdigest()
    
    # 3. Assert parity
    assert sdk_signature == expected_signature
    print(f"✅ Signature Parity Test Passed!")
    print(f"   Timestamp: {timestamp}")
    print(f"   Signature: {sdk_signature}")

if __name__ == "__main__":
    test_signature_parity()
