"""Contract test configuration — function-scoped namespace override.

Contract tests create resources with fixed names (e.g., "my-configmap",
"my-ingress") across test classes. They need per-test namespace isolation
to avoid conflicts, so we override the root conftest's module-scoped
tmp_namespace back to function scope here.
"""

from __future__ import annotations

import contextlib
import uuid
from typing import TYPE_CHECKING

import pytest

from kuberoku.k8s.client import K8sClient

if TYPE_CHECKING:
    from collections.abc import Iterator

_TEST_NS_PREFIX = "test-"


@pytest.fixture()
def tmp_namespace(request: pytest.FixtureRequest) -> Iterator[str]:
    """Function-scoped namespace for contract tests (overrides module-scoped root).

    Contract tests create resources with identical names across test classes,
    so each test needs its own namespace to avoid 409 conflicts on real K8s.
    """
    backend = request.config.getoption("--backend")
    ns_name = f"{_TEST_NS_PREFIX}{uuid.uuid4().hex[:12]}"

    if backend == "real":
        import kubernetes  # type: ignore[import-untyped]

        client = K8sClient.from_context()
        core = client._core
        body = kubernetes.client.V1Namespace(metadata=kubernetes.client.V1ObjectMeta(name=ns_name))
        core.create_namespace(body)
        yield ns_name
        with contextlib.suppress(Exception):
            core.delete_namespace(ns_name)
    else:
        yield ns_name
