"""
Live integration test for the AgentPhone Python SDK.
"""

import sys
sys.path.insert(0, ".")

from agentphone import AgentPhone, verify_webhook, construct_event, WebhookVerificationError
import json, hmac, hashlib

API_KEY = "sk_live_I-cAE7rK4QrZ0QO5EEkFM3__nZanGptm"
client = AgentPhone(api_key=API_KEY)

def ok(msg): print(f"  [PASS] {msg}")
def fail(msg): print(f"  [FAIL] {msg}")

print("\n=== Numbers ===")
numbers = client.numbers.list()
ok(f"list_numbers → {numbers.total} total")

print("\n=== Agents ===")
agents = client.agents.list()
ok(f"list_agents → {agents.total} total")

agent = client.agents.create(name="SDK Test Agent", description="Created by Python SDK test")
ok(f"create_agent → {agent.id} ({agent.name})")

fetched = client.agents.get(agent.id)
assert fetched.id == agent.id
ok(f"get_agent → {fetched.name}")

print("\n=== Phone Numbers ===")
number = client.numbers.buy(country="US")
ok(f"buy_number → {number.phone_number} ({number.id})")

attach = client.agents.attach_number(agent.id, number.id)
ok(f"attach_number → agent {attach['agentId']} ← {attach['number']['phoneNumber']}")

print("\n=== Calls ===")
calls = client.calls.list(limit=5)
ok(f"list_calls → {calls.total} total")

print("\n=== Webhooks ===")
webhook = client.webhooks.get()
if webhook:
    ok(f"get_webhook → {webhook.url} (status: {webhook.status})")
else:
    ok("get_webhook → none configured")

print("\n=== Webhook Signature Verification ===")
secret = "whsec_testsecret"
payload = json.dumps({"event": "agent.message", "channel": "sms", "timestamp": "2026-01-01T00:00:00Z", "agentId": None, "data": {"conversationId": None, "numberId": None, "from": "+15551234567", "to": "+15559876543", "message": "hi", "direction": "inbound", "receivedAt": "2026-01-01T00:00:00Z"}, "recentHistory": [], "conversationState": None}, separators=(",", ":"))
sig = "sha256=" + hmac.new(secret.encode(), payload.encode(), hashlib.sha256).hexdigest()

verify_webhook(payload, sig, secret)
ok("verify_webhook → valid signature accepted")

try:
    verify_webhook(payload, "sha256=bad", secret)
    fail("should have rejected bad signature")
except WebhookVerificationError:
    ok("verify_webhook → invalid signature rejected")

# Recompute sig after payload change
sig = "sha256=" + hmac.new(secret.encode(), payload.encode(), hashlib.sha256).hexdigest()

event = construct_event(payload, sig, secret)
assert event.event == "agent.message"
ok(f"construct_event → event.event = '{event.event}'")

print("\n=== Cleanup ===")
released = client.numbers.release(number.id)
ok(f"release_number → {number.phone_number}")

print("\nAll tests passed!\n")
