# Copyright 2026 Invoke Labs, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Batch requests and send in the background to the Voker API.

This is useful to send events to the Voker API without adding latency to your application.
"""

import queue
import threading
from typing import TypeVar

from voker.schema.base.fingerprints import Fingerprint

from .client import ApiClient

T = TypeVar("T")


class Request:
    """TODO."""

    def __init__(self, path: str, operation: str, **kwargs) -> None:
        self.path = path
        self.operation = operation
        self.kwargs = kwargs


class EventQueue(queue.Queue[Request]):
    """Queue for batching events before sending them to the Voker API."""


_STOP = object()


class EventWorker(threading.Thread):
    """Background worker that processes events from an EventQueue and sends them to the Voker API."""

    def __init__(self, client: ApiClient, event_queue: EventQueue) -> None:
        super().__init__(target=self._process, daemon=True)

        self._client = client
        self._event_queue = event_queue

        self.start()

    def _process(self) -> None:
        fingerprint = self._client.fingerprints.create()

        while True:
            item = self._event_queue.get()

            if item == _STOP:
                break

            self._process_one(item, fingerprint)

    def _process_one(self, item: Request, fingerprint: Fingerprint) -> None:
        if item.path == "events":
            if item.operation == "create":
                self._client.events.create(
                    fingerprint_id=fingerprint.fingerprint_id,
                    **item.kwargs,
                )
        elif item.path == "people":
            if item.operation == "create":
                self._client.people.create(**item.kwargs)
            elif item.operation == "update":
                self._client.people.update(**item.kwargs)
        elif item.path == "agents":
            if item.operation == "create":
                self._client.agents.create(**item.kwargs)
        elif item.path == "agent-versions":
            if item.operation == "create":
                self._client.agent_versions.create(**item.kwargs)

        # oops...

    def close(self) -> None:
        """Stop the worker and wait for it to finish processing all events in the queue."""
        self._event_queue.put(_STOP)
        self.join()  # TODO: timeout?
