"""Demo showing the full OmniLinkClient API.

Run with your Omni Key:

    export OMNI_KEY=omk_...
    python -m omnilink.examples.client_demo
"""

from __future__ import annotations

import os
import pathlib
import sys

LIB_PATH = pathlib.Path(__file__).resolve().parents[3] / "src"
if str(LIB_PATH) not in sys.path:
    sys.path.insert(0, str(LIB_PATH))

from omnilink.client import OmniLinkAPIError, OmniLinkClient

OMNI_KEY = os.environ.get("OMNI_KEY", "")
BASE_URL = os.environ.get("OMNILINK_BASE_URL", "https://www.omnilink-agents.com")


def main() -> None:
    if not OMNI_KEY:
        print("Set OMNI_KEY before running:  export OMNI_KEY=omk_...")
        sys.exit(1)

    client = OmniLinkClient(omni_key=OMNI_KEY, base_url=BASE_URL)

    # ── Chat ────────────────────────────────────────────────────────────
    print("=== Chat ===")
    try:
        response = client.chat("What is the capital of France?", agent_name="demo")
        print("Response:", response.get("text", ""))
    except OmniLinkAPIError as exc:
        print(f"Chat failed: {exc}")

    # ── Memory ──────────────────────────────────────────────────────────
    print("\n=== Memory ===")
    try:
        agents = client.list_agents()
        print(f"Agent profiles: {len(agents.get('agents', []))}")

        conversation = [
            {"role": "user",  "parts": [{"text": "Remember: favourite colour is blue."}]},
            {"role": "model", "parts": [{"text": "Got it, favourite colour is blue!"}]},
        ]
        client.set_memory("demo", conversation)
        print("Memory saved.")

        mem = client.get_memory("demo")
        print(f"Memory entries: {len(mem) if mem else 0}")

        client.clear_memory("demo")
        print("Memory cleared.")
    except OmniLinkAPIError as exc:
        print(f"Memory operation failed: {exc}")

    # ── Translate ────────────────────────────────────────────────────────
    print("\n=== Translate ===")
    try:
        result = client.translate("Bonjour le monde", target_language="English")
        print("Translation:", result.get("translation", ""))
    except OmniLinkAPIError as exc:
        print(f"Translate failed: {exc}")

    # ── TTS → STT round-trip ─────────────────────────────────────────────
    print("\n=== TTS ===")
    try:
        audio = client.synthesize_to_bytes("Hello from OmniLink!", language_code="en-US")
        print(f"Synthesized {len(audio):,} bytes of audio.")

        print("\n=== STT ===")
        result = client.transcribe(audio, mime_type="audio/mpeg")
        print("Transcription:", result.get("text", ""))
    except OmniLinkAPIError as exc:
        print(f"TTS/STT failed: {exc}")


if __name__ == "__main__":
    main()
