"""Long session with auto-extend demo.

Shows how the SDK automatically buys more time when a session is about to expire.

Usage:
    export DTELECOM_PRIVATE_KEY="0x..."
    python long_session.py
"""

import asyncio
import logging
import os
import sys

from dtelecom_stt import STTClient

# Enable logging to see auto-extend messages
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(message)s")


async def main():
    private_key = os.environ.get("DTELECOM_PRIVATE_KEY")
    if not private_key:
        print("Error: Set DTELECOM_PRIVATE_KEY environment variable")
        sys.exit(1)

    try:
        import sounddevice as sd
    except ImportError:
        print("Install sounddevice: pip install sounddevice")
        sys.exit(1)

    client = STTClient(private_key=private_key)

    # Buy 5 minutes with auto-extend enabled (default)
    # When <60s remaining, SDK will buy 5 more minutes automatically
    print("Starting 5-minute session with auto-extend...")
    print("The session will automatically extend when time is running low.")
    print("Press Ctrl+C to stop.\n")

    async with client.session(minutes=5, language="en", auto_extend=True) as stream:

        def on_result(t):
            print(f"  > {t.text}")

        stream.on_transcription(on_result)

        loop = asyncio.get_event_loop()
        audio_queue: asyncio.Queue[bytes] = asyncio.Queue()

        def audio_callback(indata, frames, time_info, status):
            pcm_bytes = indata.tobytes()
            loop.call_soon_threadsafe(audio_queue.put_nowait, pcm_bytes)

        input_stream = sd.InputStream(
            samplerate=16000,
            channels=1,
            dtype="int16",
            blocksize=320,
            callback=audio_callback,
        )

        with input_stream:
            try:
                while True:
                    chunk = await audio_queue.get()
                    await stream.send_audio(chunk)
            except KeyboardInterrupt:
                print("\nStopping...")

    print("Done.")


if __name__ == "__main__":
    asyncio.run(main())
