"""Checked and executed against installed distributions, never the source checkout."""

import asyncio
from importlib.metadata import requires, version
from typing import get_type_hints

from tarka import (
    AsyncExecutionOperationError,
    AsyncStream,
    Execution,
    ExecutionOperationError,
    Sandbox,
    Stream,
    TarkaAsyncClient,
    TarkaClient,
    types,
)
from tarka.aio.sandboxes import Execution as AsyncExecution
from tarka.aio.sandboxes import Sandbox as AsyncSandbox
from tarka.inference.v1 import inference_pb2


def check_sync(client: TarkaClient) -> None:
    models: list[types.Model] = client.models.list(timeout=10)
    text: str = client.chat.text(model="model", prompt="hi")
    completion: types.ChatCompletion = client.chat.create(
        model="model", messages=[{"role": "user", "content": "hi"}],
        tools=[{"type": "function", "function": {"name": "weather", "parameters": {"type": "object"}}}],
    )
    chunks: Stream[types.ChatChunk] = client.chat.stream(model="model", prompt="hi")
    events: Stream[types.ResponseEvent] = client.responses.stream({"model": "model", "input": "hi"})
    with events:
        for event in events:
            payload: types.JsonObject = event.data
            print(payload)
    org = client.org("org-1")
    key: types.CreatedApiKey = org.api_keys.create(label="worker")
    secret: str = key.secret
    sandbox: Sandbox = org.sandboxes.create(template="python")
    try:
        execution: Execution = sandbox.run("print(1)", timeout=30)
    except ExecutionOperationError as error:
        execution = error.resume(timeout=60)
    state: types.ExecutionStatus = execution.status
    raw: inference_pb2.ListModelsResponse = client.grpc.inference.ListModels(inference_pb2.ListModelsRequest())
    client.chat.text(prompt="hi")  # type: ignore[call-arg]
    client.chat.text(model=123, prompt="hi")  # type: ignore[arg-type]
    client.models.list(timeout="slow")  # type: ignore[arg-type]
    org.api_keys.create(org_id="other-org")  # type: ignore[call-arg]
    client.inference.ListModels()  # type: ignore[attr-defined]
    wrong: int = models[0].id  # type: ignore[assignment]
    print(text, completion, chunks, secret, state, raw, wrong)


async def check_async(client: TarkaAsyncClient) -> None:
    models: list[types.Model] = await client.models.list()
    stream: AsyncStream[str] = client.chat.stream_text(model="model", prompt="hi")
    async with stream:
        async for text in stream:
            print(text)
    sandbox: AsyncSandbox = await client.org("org-1").sandboxes.get("sandbox-1")
    try:
        execution: AsyncExecution = await sandbox.run("print(1)")
    except AsyncExecutionOperationError as error:
        execution = await error.resume(timeout=60)
    state: types.ExecutionStatus = execution.status
    print(models, state)


assert version("tarka-sdk") == "0.9.0"
assert {item.split("<")[0].split(">=")[0] for item in requires("tarka-sdk") or []} == {
    "grpcio", "protobuf", "googleapis-common-protos", "httpx", "httpx-sse", "pocketbase",
}
assert get_type_hints(types.Model)["id"] is str
assert types.Model(id="test").to_dict()["id"] == "test"
assert types.AudioData(data=b"\x00\xff").to_dict(json_safe=True)["data"] == "AP8="
assert inference_pb2.Model.FromString(inference_pb2.Model(id="wire").SerializeToString()).id == "wire"

# Construct clients and verify channel ownership without sending any requests.
with TarkaClient("package-fixture-token") as client:
    assert callable(client.models.list)
    assert callable(client.grpc.inference.ListModels)
    assert not hasattr(client, "inference")


async def construct_async() -> None:
    async with TarkaAsyncClient("package-fixture-token") as client:
        assert callable(client.models.list)


asyncio.run(construct_async())

from tarka import RuntimeClient, AsyncRuntimeClient, RuntimePermission
assert RuntimePermission("fixture", "invoke").action == "invoke"
assert callable(RuntimeClient.start) and callable(AsyncRuntimeClient.start)

from tarka import Database
with Database("https://example.tarka.run", "fixture") as database:
    assert database.collection("notes").collection_id_or_name == "notes"
