# backend/tests/conftest.py
import os

# 테스트는 RAG 임베딩을 heuristic(결정적·오프라인)으로 강제 — Ollama embeddings 호출 회피.
os.environ.setdefault("EMBED_PROVIDER", "heuristic")
os.environ.setdefault("AGENT_PROVIDER", "scripted")

import pytest  # noqa: E402
from fastapi.testclient import TestClient  # noqa: E402
from sqlmodel import Session, SQLModel, create_engine
from sqlmodel.pool import StaticPool

from app import seed as seed_mod
from app.db import get_session
from app.llm.heuristic import HeuristicProvider
from app.llm.provider import get_provider
from app.main import app


@pytest.fixture(autouse=True)
def _clear_llm_overlay():
    """설정 페이지 LLM 런타임 오버레이를 테스트마다 비운다(전역 상태 누수 방지·결정성)."""
    from app import runtime_config

    runtime_config.clear()
    yield
    runtime_config.clear()


@pytest.fixture()
def session():
    engine = create_engine(
        "sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool
    )
    SQLModel.metadata.create_all(engine)
    with Session(engine) as s:
        yield s, engine


@pytest.fixture()
def client(session):
    s, engine = session
    # 테스트 세션을 주입해 시드(정본 시그니처: run_seed(session=..., reset=True)).
    with Session(engine) as seed_s:
        seed_mod.run_seed(session=seed_s, reset=True)

    def _get_session():
        with Session(engine) as ss:
            yield ss

    app.dependency_overrides[get_session] = _get_session
    # LLM은 기본적으로 heuristic 강제(테스트 결정성).
    app.dependency_overrides[get_provider] = lambda: HeuristicProvider()
    yield TestClient(app)
    app.dependency_overrides.clear()


@pytest.fixture()
def client_auth(session, monkeypatch):
    """phase-15: AUTH_ENABLED=true 클라이언트 — 자격(지우 admin / 현우 member) 시드.
    TestClient 가 쿠키 잼을 유지하므로 로그인 후 세션 쿠키가 이어진다."""
    s, engine = session
    monkeypatch.setenv("AUTH_ENABLED", "true")
    from app.config import get_settings

    get_settings.cache_clear()
    with Session(engine) as seed_s:
        seed_mod.run_seed(session=seed_s, reset=True)  # AUTH_ENABLED → UserCredential 생성

    def _get_session():
        with Session(engine) as ss:
            yield ss

    app.dependency_overrides[get_session] = _get_session
    app.dependency_overrides[get_provider] = lambda: HeuristicProvider()
    yield TestClient(app)
    app.dependency_overrides.clear()
    get_settings.cache_clear()
