"""Async queue-backed single-writer for append-mode files."""

from __future__ import annotations

import asyncio
from pathlib import Path

import aiofiles


class AsyncQueuedFileWriter:
    """Async context manager: queue-backed single-writer for append-mode files.

    Intended for high throughput file writers.

    Workers call the synchronous ``submit()`` method to enqueue lines without
    blocking the event loop.  A single writer coroutine drains the queue and
    performs the actual async file I/O.
    """

    def __init__(self, path: Path):
        self._path = path
        self._queue: asyncio.Queue[str | None] = asyncio.Queue()
        self._writer_task: asyncio.Task | None = None
        self._file = None

    async def __aenter__(self):
        self._path.parent.mkdir(parents=True, exist_ok=True)
        self._file = await aiofiles.open(self._path, mode="a")
        self._writer_task = asyncio.create_task(self._writer_loop())
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self._queue.put(None)
        if self._writer_task:
            await self._writer_task
        if self._file:
            await self._file.close()
        return False

    def submit(self, line: str) -> None:
        """Non-blocking enqueue. Called by workers from the event loop."""
        self._queue.put_nowait(line)

    async def _writer_loop(self) -> None:
        while True:
            item = await self._queue.get()
            if item is None:
                break
            await self._file.write(item)
            await self._file.flush()
