"""pytest 共享夹具。

- `tmp_db`：隔离 sqlite，替换模块级 DEFAULT_DB_PATH
- `fake_secrets`：写 `.vault/secrets.json`，让 `credentials.get()` 可测
"""

from __future__ import annotations

import json
from pathlib import Path

import pytest


@pytest.fixture(autouse=True)
def tmp_db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
    db_path = tmp_path / "xq.db"
    monkeypatch.setenv("XIANGQIN_DB_PATH", str(db_path))
    from xiangqin import db as db_module

    db_module.DEFAULT_DB_PATH = db_path
    db_module.init_db(db_path)
    yield db_path


@pytest.fixture(autouse=True)
def _bypass_realname_by_default(monkeypatch: pytest.MonkeyPatch):
    """FEAT-034：默认 bypass 实名闸门，保护既有 mail/admin 测试。
    需要测闸门真实行为的测试文件（如 test_realname_mail_integration.py）
    在测试体内 monkeypatch 回真实 realname.assert_user_verified 即可。
    """
    from xiangqin import realname

    monkeypatch.setattr(realname, "assert_user_verified", lambda uid: None)


@pytest.fixture
def fake_secrets(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
    """写假的 .vault/secrets.json 并指 credentials.py 去读它。"""
    p = tmp_path / "secrets.json"
    p.write_text(
        json.dumps(
            {
                "_generated_at": "2026-04-23T00:00:00+00:00",
                "_note": "test fixture",
                "aliyun": {
                    "access_key_id": "TEST_AK",
                    "access_key_secret": "TEST_SK",
                    "default_region": "cn-hangzhou",
                },
                "aliyun_sms": {
                    "access_key_id": "TEST_SMS_AK",
                    "access_key_secret": "TEST_SMS_SK",
                },
                "alipay": {
                    "app_id": "2021000TEST",
                    "app_private_key": "-----BEGIN PRIVATE KEY-----\\nX\\n-----END PRIVATE KEY-----",
                    "alipay_public_key": "-----BEGIN PUBLIC KEY-----\\nY\\n-----END PUBLIC KEY-----",
                },
            }
        )
    )
    monkeypatch.setenv("XIANGQIN_SECRETS_PATH", str(p))
    # 清掉 @cache
    from xiangqin import credentials

    credentials._load.cache_clear()
    yield p
    credentials._load.cache_clear()
