import asyncio
import logging
import os
from collections.abc import AsyncIterable, AsyncIterator
from pathlib import Path
from typing import cast

import pytest
from dishka import AsyncContainer
from fastapi import FastAPI

from template_project.web_api.configuration import load_configuration
from template_project.web_api.entry_point import make_server
from tests.web_api.helpers import get_unique_email
from tests.web_api.ioc import make_ioc


@pytest.fixture(scope="session")
async def dishka_container(backend: FastAPI) -> AsyncIterable[AsyncContainer]:
    path = Path(os.environ["CONFIGURATION_PATH"])
    configuration = load_configuration(path)
    ioc = make_ioc(configuration, backend)
    yield ioc
    await ioc.close()


@pytest.fixture(scope="session")
async def backend() -> AsyncIterator[FastAPI]:
    logging.getLogger("httpx").setLevel(logging.WARNING)
    logging.getLogger("httpcore").setLevel(logging.WARNING)

    configuration = load_configuration(Path(os.environ["CONFIGURATION_PATH"]))
    server = make_server(configuration)
    asyncio.create_task(server.serve())  # type: ignore[unused-awaitable]
    yield cast(FastAPI, server.config.app)


@pytest.fixture
def unique_email() -> str:
    return get_unique_email()
