"""
Test configuration and shared fixtures.

Patches are applied at module level (before any app code is imported) so that
database.py's module-level create_engine / SELECT-1 probe never touches a real
PostgreSQL server.  All other external dependencies (Redis, LangGraph, LLM
calls) are mocked per-test via unittest.mock.patch inside test_api.py.
"""

import os
import sys
from types import SimpleNamespace
from unittest.mock import MagicMock, patch

# ── 1. Environment variables ──────────────────────────────────────────────────
# Must be set before any app module is imported so that os.getenv() calls at
# module level pick up test values instead of a missing .env file.
os.environ.setdefault("DATABASE_URL", "postgresql://test:test@localhost/test_db")
os.environ.setdefault("JWT_SECRET", "test-secret-for-unit-tests")
os.environ.setdefault("ACTIVE_LLM_PROVIDER", "deepseek")
os.environ.setdefault("DEEPSEEK_API_KEY", "sk-test-deepseek")
os.environ.setdefault("OPENAI_API_KEY", "sk-test-openai")
os.environ.setdefault("DEEPSEEK_MODEL", "deepseek-chat")
os.environ.setdefault("REDIS_HOST", "localhost")
os.environ.setdefault("REDIS_PORT", "6379")
os.environ.setdefault("REDIS_DB", "0")

# ── 2. Mock database before importing any app module ─────────────────────────
# database.py runs create_engine() + "SELECT 1" at import time.
# We intercept create_engine so no real TCP connection is attempted.
_mock_engine = MagicMock()
_mock_conn = MagicMock()
_mock_engine.connect.return_value.__enter__ = MagicMock(return_value=_mock_conn)
_mock_engine.connect.return_value.__exit__ = MagicMock(return_value=False)

with patch("sqlalchemy.create_engine", return_value=_mock_engine):
    import database  # engine is now the mock; SELECT 1 uses MagicMock → no error

# Replace init_db so that main.py's module-level init_db() call is a no-op.
# This must happen before importing main.
database.init_db = MagicMock()

# ── 3. Import app (safe now) ──────────────────────────────────────────────────
import pytest
from httpx import AsyncClient, ASGITransport

import main
from main import app
from dependencies import verify_jwt_token, enforce_token_quota
from database import get_db
import services.hr_graph as hr_graph

# ── 4. Shared test constants ──────────────────────────────────────────────────
TEST_COMPANY_ID = 99
TEST_CONV_ID = "conv-test-uuid-abc123"

# JWT payload returned by the overridden dependency
FAKE_JWT_PAYLOAD = {
    "company_id": TEST_COMPANY_ID,
    "user_id": TEST_COMPANY_ID,
    "role_id": 1,
    "user_type": "admin",
    "company_name": "Test Company Ltd",
}

# A minimal conversation object that FastAPI's jsonable_encoder can serialise.
# SimpleNamespace → vars() → dict → JSON  ✓
FAKE_CONVERSATION = SimpleNamespace(
    id=TEST_CONV_ID,
    company_id=TEST_COMPANY_ID,
    title="Test Chat",
    is_deleted=0,
    created_at=None,
    updated_at=None,
)

# ── 5. Fixtures ───────────────────────────────────────────────────────────────

@pytest.fixture
def mock_db():
    """Throwaway SQLAlchemy session mock — never touches a real database."""
    return MagicMock()


@pytest.fixture(autouse=True)
def _no_real_structured_date_calls(monkeypatch):
    """Repo-wide default for the tier-2 structured date-extraction call
    (services.ai_service.extract_structured_date_fields, called from
    hr_graph.leave_action_node). Its gate is deliberately wide — any
    weekday name, or a word like "next"/"last"/"quarter", anywhere in an
    apply-leave query (see leave_action_node's _looks_like_a_date_query) —
    so plenty of tests whose queries happen to contain one of those words,
    across multiple test files, trip it even though they're not testing
    date logic at all. Without this default, those tests silently make a
    real, unmocked network call to whichever provider is active (caught
    gracefully by the real function's own try/except, so they still pass —
    just slowly, non-deterministically, and against a real external
    endpoint). Defaults to "nothing extracted" so tier 2 always politely
    declines and control falls through exactly as if it didn't exist.
    Tests that specifically want to exercise tier 2 override this with
    their own monkeypatch.setattr(hr_graph, "extract_structured_date_fields", ...)
    — same monkeypatch instance, later call in the same test wins.
    Autouse, so it applies to every test in the whole suite; harmless
    no-op for anything that never imports/calls hr_graph.leave_action_node."""
    async def _empty(query, today):
        return {
            "day_offset": None, "target_weekday": None, "weekday_relation": None,
            "ordinal": None, "month_offset": None, "duration_days": None,
        }, None
    monkeypatch.setattr(hr_graph, "extract_structured_date_fields", _empty)


# Default quota check result used by overridden tests that aren't exercising
# quota logic itself — always "allowed", no warnings.
FAKE_QUOTA_CHECK = {"allowed": True, "breaches": [], "warnings": [], "policy_source": "unlimited"}


@pytest.fixture
def override_deps(mock_db):
    """
    Override the FastAPI dependencies used by every protected endpoint:
      - verify_jwt_token   → returns FAKE_JWT_PAYLOAD (bypasses real JWT decode)
      - get_db             → returns the mock_db session
      - enforce_token_quota → always allows (mock_db can't run real SQL aggregation)
    Cleared after each test so overrides don't leak.
    """
    app.dependency_overrides[verify_jwt_token] = lambda: FAKE_JWT_PAYLOAD
    app.dependency_overrides[get_db] = lambda: mock_db
    app.dependency_overrides[enforce_token_quota] = lambda: FAKE_QUOTA_CHECK
    yield
    app.dependency_overrides.clear()


@pytest.fixture
async def client(override_deps):
    """Async HTTPX client wired directly to the FastAPI app (no real TCP).

    Carries a default Authorization header: verify_jwt_token is overridden
    (see override_deps) so its value is never actually decoded, but routes
    like /ping and /hr-assist-stream also read the raw header directly (to
    forward the caller's own token to erp-api) via a plain Header(...)
    parameter, which dependency_overrides can't intercept. Per-request
    headers passed to individual calls still take precedence over this.
    """
    async with AsyncClient(
        transport=ASGITransport(app=app),
        base_url="http://testserver",
        headers={"Authorization": "Bearer test-fixture-token"},
    ) as ac:
        yield ac


@pytest.fixture
async def unauth_client():
    """Client with NO dependency overrides — used to verify 401 responses."""
    async with AsyncClient(
        transport=ASGITransport(app=app),
        base_url="http://testserver",
    ) as ac:
        yield ac
