"""Integration tests against live x402 STT proxy on Base Sepolia.

Requirements:
  - Proxy running at PROXY_URL (default: https://x402stt.dtelecom.org)
  - Test wallet funded with testnet USDC on Base Sepolia

Run:
    export TEST_CLIENT_PRIVATE_KEY="0x..."
    pytest tests/test_integration.py -v -s

Skip if server unreachable (CI-safe).
"""

import asyncio
import json
import os
import time
from pathlib import Path

import httpx
import pytest
import websockets

from dtelecom_stt import STTClient, Transcription
from dtelecom_stt.audio import load_wav, silence, stream_realtime

PROXY_URL = os.getenv("PROXY_URL", "https://x402stt.dtelecom.org")
PRIVATE_KEY = os.getenv("TEST_CLIENT_PRIVATE_KEY", "")
AUDIO_DIR = Path(__file__).parent.parent.parent / "test_data" / "english"


@pytest.fixture(scope="module", autouse=True)
def check_prerequisites():
    """Skip all tests if proxy unreachable or no private key."""
    if not PRIVATE_KEY:
        pytest.skip("TEST_CLIENT_PRIVATE_KEY not set")
    try:
        resp = httpx.get(f"{PROXY_URL}/health", timeout=5)
        if resp.status_code != 200:
            pytest.skip(f"Proxy unhealthy at {PROXY_URL}")
    except Exception:
        pytest.skip(f"Proxy unreachable at {PROXY_URL}")


@pytest.fixture(scope="module")
def client():
    return STTClient(private_key=PRIVATE_KEY, url=PROXY_URL)


# ── Tests ─────────────────────────────────────────────────────────────


@pytest.mark.asyncio
async def test_pricing(client):
    """Verify pricing endpoint returns expected structure."""
    info = await client.pricing()
    assert info.price_per_minute_usd > 0
    assert info.currency == "USDC"
    assert info.min_minutes > 0
    assert info.max_minutes > info.min_minutes
    print(f"\nPricing: ${info.price_per_minute_usd}/min, "
          f"min={info.min_minutes}min, max={info.max_minutes}min")


@pytest.mark.asyncio
async def test_health(client):
    """Verify health endpoint."""
    data = await client.health()
    assert data["status"] == "ok"
    print(f"\nHealth: {data}")


@pytest.mark.asyncio
async def test_session_and_transcribe():
    """Buy session, stream audio, verify transcription."""
    if not PRIVATE_KEY:
        pytest.skip("No private key")

    wav_path = AUDIO_DIR / "1272-128104-0006.wav"
    if not wav_path.exists():
        pytest.skip(f"Test audio not found: {wav_path}")

    client = STTClient(private_key=PRIVATE_KEY, url=PROXY_URL)

    async with client.session(minutes=5, language="en", auto_extend=False) as stream:
        transcriptions = []

        async for t in stream.transcribe_file(str(wav_path)):
            transcriptions.append(t)
            print(f"  [{t.start}s] {t.text}")

    assert len(transcriptions) > 0, "No transcriptions received"

    all_text = " ".join(t.text for t in transcriptions).lower()
    # Reference: "on the general principles of art mister quilter writes with equal lucidity"
    assert any(
        word in all_text for word in ["quilter", "principles", "art", "lucidity"]
    ), f"Transcription doesn't match reference: {all_text}"

    print(f"\nGot {len(transcriptions)} transcription(s): {all_text}")
