"""
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")
# The key above is fake: output moderation would call OpenAI with it after every turn.
os.environ["OUTPUT_MODERATION_ENABLED"] = "false"
# Blank, not left to .env: MODERATION_PROVIDER=race there would send every unmocked
# classify test to the real race-api. Blank follows ACTIVE_LLM_PROVIDER (deepseek: none).
os.environ["MODERATION_PROVIDER"] = ""
# The code default, not .env: NON_HR_LIVE_SOURCES=none there turned off the
# weather/time/place sources the live_info tests exercise.
os.environ["NON_HR_LIVE_SOURCES"] = "all"
# The fixed refusal texts, not a model call per blocked message.
os.environ["GUARDRAIL_MODEL_REPLIES"] = "false"
# Off, whatever .env says: the app graph is compiled at import, and with it on
# every test would need the checkpoint tables. Tests that want it build their
# own graph with a saver (tests/test_graph_checkpointer.py).
os.environ["LANGGRAPH_CHECKPOINTER"] = "off"
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")
# Empty on purpose: the test suite never talks to a real Redis, and this keeps a
# developer's exported production REDIS_PASSWORD out of the test environment.
os.environ["REDIS_PASSWORD"] = ""
os.environ["REDIS_USERNAME"] = ""

# ── Redis: faked before ANY app module is imported ───────────────────────────
# Twelve service modules open a real Redis connection at IMPORT time
# (`_r = _make_client()` at module scope, plus cache_service's bare `r`), and
# a real server is listening on localhost:6379 in this environment. Fixtures
# cannot help with that - they run long after the import.
#
# Left alone it exhausts the machine. Every pytest process opens a dozen real
# sockets that go to TIME_WAIT on exit, and Windows' dynamic port range is
# only ~16k: after a few dozen runs the range fills (measured: 8109 sockets
# in TIME_WAIT, 89 of them to 6379) and the next connect blocks in the
# kernel. That is the intermittent whole-suite freeze - a run that normally
# takes 3 seconds sitting past 50 with no progress, and with faulthandler's
# own watchdog thread unable to fire, because nothing in the process is
# running Python at all.
#
# Patching the class itself, rather than each module's client, is what makes
# it airtight: it covers the import-time clients, the lazy _make_client()
# reconnects, and anything that builds its own client later. redis.exceptions
# is untouched, so main.py's AuthenticationError handling still sees the real
# classes.
import redis as _redis

class _FakePipeline:
    """Buffers like the real one and applies on execute(). Only the three
    commands redis_chat_service queues are implemented; anything else should
    fail loudly rather than silently do nothing."""

    def __init__(self, client):
        self._client = client
        self._queued = []

    def rpush(self, key, *values):
        self._queued.append(("rpush", key, values))
        return self

    def ltrim(self, key, start, end):
        self._queued.append(("ltrim", key, (start, end)))
        return self

    def expire(self, key, ttl):
        return self

    def execute(self):
        for op, key, args in self._queued:
            if op == "rpush":
                self._client.lists.setdefault(key, []).extend(str(v) for v in args)
            elif op == "ltrim":
                start, end = args
                current = self._client.lists.get(key, [])
                stop = None if end == -1 else end + 1
                self._client.lists[key] = current[start:stop]
        self._queued = []
        return []


class _FakeRedis:
    """Just the commands these modules actually issue, with
    decode_responses=True semantics (everything comes back as str)."""

    def __init__(self):
        self.store = {}
        self.lists = {}

    def ping(self):
        return True

    def get(self, key):
        return self.store.get(key)

    def set(self, key, value, ex=None, nx=False, **kwargs):
        if nx and key in self.store:
            return None
        self.store[key] = str(value)
        return True

    def setex(self, key, ttl, value):
        return self.set(key, value)

    def delete(self, *keys):
        removed = 0
        for key in keys:
            removed += bool(self.store.pop(key, None) is not None)
            self.lists.pop(key, None)
        return removed

    def exists(self, key):
        return int(key in self.store or key in self.lists)

    def lrange(self, key, start, end):
        items = self.lists.get(key, [])
        return items[start:] if end == -1 else items[start:end + 1]

    def keys(self, pattern="*"):
        return list(self._matching(pattern))

    def scan_iter(self, pattern="*"):
        return iter(list(self._matching(pattern)))

    def _matching(self, pattern):
        import fnmatch
        names = list(self.store) + list(self.lists)
        return [k for k in names if fnmatch.fnmatch(k, pattern)]

    def pipeline(self):
        return _FakePipeline(self)



_redis.Redis = lambda *a, **kw: _FakeRedis()


# ── 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(scope="session")
def event_loop():
    """One event loop for the whole session, not one per test.

    pytest-asyncio's default is a fresh loop per async test, and on Windows
    every ProactorEventLoop builds its self-pipe out of a loopback socket
    pair. Closing the loop leaves those in TIME_WAIT for the system's two
    minutes, so this suite - about four thousand tests, nearly all async -
    burns roughly four thousand ephemeral ports per run (measured: 2000
    loops -> 1981 new TIME_WAIT entries, and a full run moved the machine's
    total by 4292).

    Windows' dynamic range is only ~16k ports, so two or three runs in a row
    exhaust it and the next socket operation blocks in the kernel. That is
    the intermittent freeze: a file that takes 3 seconds sitting past 50
    with no output, at a different test each time, and with faulthandler's
    watchdog unable to print anything because the process is stopped below
    Python rather than deadlocked inside it.

    One loop for the session costs one socket pair per run instead of one
    per test. Scoped here rather than through pytest.ini's
    asyncio_default_fixture_loop_scope, which pytest-asyncio 0.21.1 does not
    understand - it is already in that file and already warned about as an
    unknown option on every run.
    """
    import asyncio

    loop = asyncio.new_event_loop()
    yield loop
    loop.close()


@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)


@pytest.fixture(autouse=True)
def _no_real_last_resolved_date_state(monkeypatch):
    """Repo-wide default for services.last_resolved_date_state — the
    cross-turn "date we were just discussing" memory that attendance.py/
    attendance_explain.py/punch_details.py/hr_graph.py read and write.
    Despite this file's own comment above claiming "the test suite never
    talks to a real Redis", a real Redis IS reachable at localhost:6379 in
    this environment, and this module's writes are a plain side effect of
    resolving a date — not something individual tests opt into. Many test
    files reuse one fixed company_id/conversation_id across every test in
    the file (e.g. test_punch_details.py's `state` fixture), so one test
    resolving a real date silently poisoned a LATER test in the same file
    that asserted "no date -> date=None" behavior (observed: got back
    whatever date an earlier test in the run had resolved, instead of
    None). Defaults every test to "no Redis" — this module already
    degrades gracefully to a no-op when _get_redis() returns None, so this
    is a pure no-op for tests that don't care about the carry-over feature
    itself. A test that specifically wants to exercise it should patch its
    own FakeRedis via monkeypatch.setattr(last_resolved_date_state,
    "_get_redis", ...) — same monkeypatch instance, later call wins."""
    import services.last_resolved_date_state as last_resolved_date_state
    monkeypatch.setattr(last_resolved_date_state, "_get_redis", lambda: None)


# ── Redis: per-test, in-memory, never the real server ────────────────────────
# The comment at the top of this file claims "the test suite never talks to a
# real Redis". That has not been true for a while: a real server IS listening
# on localhost:6379 in this environment (the _no_real_last_resolved_date_state
# fixture below already says so), and every state module falls back to it the
# moment a test does not stub it by hand.
#
# What that cost, in order of how badly it misleads:
#
#   * TWO PYTEST RUNS AT ONCE DESTROY EACH OTHER. The keys are derived from
#     company_id + conversation_id, and the fixtures across this suite reuse a
#     handful of both ("conv-1", company 1). Two concurrent runs are therefore
#     writing each other's slots, cancel states and manager actions. Measured:
#     the same tree that fails 15 tests on its own reports 233 when a second
#     run is in flight. Any "baseline" captured that way is fiction.
#   * RUN-TO-RUN VARIANCE. State outlives the process, so whether a test sees
#     a stale slot depends on what ran before it - in a previous run, hours
#     ago.
#   * HANGS. A run that reconnects mid-suite can sit on socket timeouts; one
#     observed run took over ten minutes against 22 seconds for the next.
#
# A fake rather than None: these modules already degrade to no-ops when the
# client is missing, so returning None would quietly switch off the state
# carrying that multi-turn tests depend on and change what they prove. The
# fake keeps the semantics and drops only the sharing - one fresh store per
# test, so nothing crosses a test, a run, or a concurrent run.
#
# A test that wants its own stub still overrides this: same monkeypatch
# instance, and the fixture's setattr happens first, so the test's wins.

#: The state stores, each of which reaches Redis through its own module-level
#: `_get_redis()`. last_resolved_date_state is deliberately NOT here - it has
#: its own fixture below that disables it outright, and enabling it would turn
#: the date carry-over feature back on underneath tests written without it.
_REDIS_STATE_MODULES = (
    "services.leave_slot_service",
    "services.slot_store",
    "services.regularisation_store",
    "services.redis_chat_service",
    "services.leave_type_clarify_state",
    "services.leave_history_clarify_state",
    "services.leave_eligibility_clarify_state",
    "services.leave_disambiguation_state",
    "services.leave_cancel_state",
    "services.bare_verb_clarify_state",
)


@pytest.fixture(autouse=True)
def fake_redis(monkeypatch):
    """One fresh in-memory Redis per test, shared by every state module in
    that test (they key off company_id/conversation_id, and some flows write
    in one module and read in another, so they must see one store)."""
    import importlib

    client = _FakeRedis()
    for name in _REDIS_STATE_MODULES:
        module = importlib.import_module(name)
        monkeypatch.setattr(module, "_get_redis", lambda _c=client: _c, raising=False)
        # The cached module-level handle, so nothing can hand back the real
        # client that a previous test may already have connected.
        if hasattr(module, "_r"):
            monkeypatch.setattr(module, "_r", client, raising=False)

    # cache_service holds a plain module-level `r` built at import time
    # instead of a _get_redis() accessor.
    import services.cache_service as cache_service
    monkeypatch.setattr(cache_service, "r", client, raising=False)
    # The submit claim's in-process half outlives a test like any module
    # global; a fresh store gets fresh claims.
    import services.leave_submit_claim as leave_submit_claim
    monkeypatch.setattr(leave_submit_claim, "_claims", {})
    # Same for the apply-leave draft's in-process fallback copy.
    import services.leave_slot_service as leave_slot_service
    monkeypatch.setattr(leave_slot_service, "_memory", {})
    return client


# 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
