"""Shared pytest fixtures."""

from __future__ import annotations

import os
from collections.abc import Iterator
from pathlib import Path

import numpy as np
import pytest


@pytest.fixture(autouse=True)
def _isolated_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
    """Per-test sqlite + blob storage so tests don't share state.

    Setting these env vars before ``Settings`` is first read in the test gives
    each test its own DB file and blob root. We also clear the lru_cache on
    `get_settings`, the engine, and the sessionmaker so the fresh paths take
    effect even if a previous test already loaded settings.
    """
    db_path = tmp_path / "test.sqlite"
    blob_dir = tmp_path / "blobs"
    monkeypatch.setenv("DATABASE_URL", f"sqlite:///{db_path}")
    monkeypatch.setenv("BLOB_STORAGE_DIR", str(blob_dir))
    monkeypatch.setenv("STORAGE_LOCAL_DIR", str(tmp_path / "storage"))
    monkeypatch.setenv("API_KEYS", "")
    # The async API path is exercised by the test suite, so default it on
    # here. Production keeps ``QUEUE_ENABLED=false`` so the route falls back
    # to the inline pipeline when no Redis is configured.
    monkeypatch.setenv("QUEUE_ENABLED", "true")
    # Force Celery to run tasks inline so we don't need a broker.
    monkeypatch.setenv("CELERY_TASK_ALWAYS_EAGER", "true")

    from ocr_sprint.config import get_settings
    from ocr_sprint.db.base import reset_engine_cache
    from ocr_sprint.worker.celery_app import celery_app

    get_settings.cache_clear()
    reset_engine_cache()
    # `celery_app` is built once at import-time, so flip the eager flag on the
    # already-instantiated instance for this test.
    celery_app.conf.task_always_eager = True
    celery_app.conf.task_eager_propagates = True

    yield

    get_settings.cache_clear()
    reset_engine_cache()
    os.environ.pop("CELERY_TASK_ALWAYS_EAGER", None)


@pytest.fixture
def blank_bgr_image() -> np.ndarray:
    """A 600x800 white BGR image (uint8) — useful for preprocessing smoke tests."""
    return np.full((600, 800, 3), 255, dtype=np.uint8)


@pytest.fixture
def sample_sprint_text() -> str:
    """Realistic-but-synthetic OCR text for regex extractor tests."""
    return (
        "KEPOLISIAN NEGARA REPUBLIK INDONESIA\n"
        "DAERAH JAWA BARAT\n"
        "RESOR BANDUNG\n"
        "\n"
        "SURAT PERINTAH\n"
        "Nomor : Sprin/123/IV/2025/Reskrim\n"
        "\n"
        "DASAR :\n"
        "1. Undang-Undang Nomor 2 Tahun 2002 tentang Kepolisian Negara Republik Indonesia.\n"
        "2. Peraturan Kapolri Nomor 6 Tahun 2017 tentang Susunan Organisasi.\n"
        "3. Laporan Polisi Nomor LP/123/IV/2025/Reskrim tanggal 20 April 2025.\n"
        "\n"
        "DIPERINTAHKAN :\n"
        "Kepada : 1. Nama anggota tersebut di bawah ini.\n"
        "\n"
        "Untuk : Melaksanakan penyelidikan tindak pidana.\n"
        "\n"
        "PERIHAL : Pelaksanaan penyelidikan kasus pencurian.\n"
        "\n"
        "Bandung, 21 April 2025\n"
        "KEPALA KEPOLISIAN RESOR BANDUNG\n"
        "\n"
        "Drs. BUDI SANTOSO\n"
        "AKBP NRP 12345678\n"
    )
