"""Shared pytest fixtures for the InvestmentWebsite test suite.

Scope note: this fixture layer is meant to document existing behaviour of
create_app() as-is. It deliberately avoids loading the real .env file so
tests never depend on (or exercise) real SMTP/FTP credentials, and never
perform real network I/O.
"""
import os
import sys
import tempfile
import importlib.util
from pathlib import Path

import pytest

# Install boundaries before collection can import any application/test module.
PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))
_support = PROJECT_ROOT / "tests" / "_support" / "safety.py"
_spec = importlib.util.spec_from_file_location("investment_test_safety", _support)
safety = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(safety)
_inherited_data = os.environ.pop("DATA_DIR", None)
_inherited_request_logs = os.environ.pop("REQUEST_LOG_DIR", None)
_protected = [PROJECT_ROOT.parent / "InvestmentData", PROJECT_ROOT / "instances",
              PROJECT_ROOT / "logs", PROJECT_ROOT / "static" / "images",
              PROJECT_ROOT / "InvestmentManager" / "alerts",
              PROJECT_ROOT / "InvestmentManager" / "knowledge_center",
              PROJECT_ROOT / "InvestmentManager" / "scrapers" / "data"]
if _inherited_data:
    _protected.append(Path(_inherited_data).absolute())
if _inherited_request_logs:
    _protected.append(Path(_inherited_request_logs).absolute())
safety.install(PROJECT_ROOT, _protected)
os.environ["FLASK_ENV"] = "development"
os.environ["SECRET_KEY"] = "test-secret-key-not-for-production"
os.environ["INVESTMENT_LEGACY_STORAGE"] = "1"

from modules.core import storage_paths  # noqa: E402

# Importing create_app imports route/logger modules with a few legacy
# import-time filesystem side effects. Keep those effects in a disposable
# runtime root while preserving normal storage path semantics for the tests
# themselves once import is complete.
_IMPORT_TIME_RUNTIME = tempfile.TemporaryDirectory(prefix="investment_pytest_import_runtime_")
_PROJECT_REPO_ROOT = storage_paths.REPO_ROOT
storage_paths.REPO_ROOT = Path(_IMPORT_TIME_RUNTIME.name)
try:
    from modules.core.app_factory import create_app  # noqa: E402
finally:
    storage_paths.REPO_ROOT = _PROJECT_REPO_ROOT

from flask import Flask  # noqa: E402
from flask.testing import FlaskClient  # noqa: E402
from werkzeug.datastructures import Headers  # noqa: E402


class BrowserLikeClient(FlaskClient):
    """Test client that behaves like a same-origin browser.

    A real browser labels every mutating request (Sec-Fetch-Site / Origin); the CRM CSRF guard rejects mutating requests that
    carry no label at all (middleware/request_guard.py). Without this, every existing test that POSTs through the plain Flask
    client would be an unlabeled request. The label is added ONLY when the test did not set Origin, Referer or Sec-Fetch-Site
    itself, so tests of hostile / unlabeled requests stay explicit. Set `client.browser_headers = False` to send bare requests.
    """
    browser_headers = True
    _LABELS = {'origin', 'referer', 'sec-fetch-site'}

    def open(self, *args, **kwargs):
        method = str(kwargs.get('method', 'GET')).upper()
        if self.browser_headers and method in {'POST', 'PUT', 'PATCH', 'DELETE'}:
            headers = Headers(kwargs.get('headers') or {})
            if not any(name.lower() in self._LABELS for name in headers.keys()):
                headers['Sec-Fetch-Site'] = 'same-origin'
            kwargs['headers'] = headers
        return super().open(*args, **kwargs)


Flask.test_client_class = BrowserLikeClient


# ---------------------------------------------------------------------------
# Safety infrastructure for the storage contract test suite (tests/storage/).
#
# Discovered while building that suite: modules/core/request_logging.py attaches real
# TimedRotatingFileHandlers (to the *actual* logs/website/*.log and
# logs/error.log files) at import time, and every test that exercises a
# request through the `client` fixture triggers app.after_request ->
# modules.core.request_logging.after_request -> a real, unguarded write to those files.
# Verified empirically: running just tests/test_app_factory_smoke.py grew
# logs/website/access.log from 16413 to 16717 bytes. This predates this test
# suite and affects the whole existing test session, not just new tests.
#
# The fixture below is test infrastructure only: it detaches the
# already-configured logging handlers and monkeypatches the central storage
# path resolver (modules/core/storage_paths.py) -- no production source
# file is edited. It is session-scoped and autouse so it protects the
# entire test run, not just tests/storage/.
#
# Post storage-path-layer refactor: InvestmentWebsite/services/platform_logger.py,
# InvestmentManager/leady_pipeline.py and InvestmentManager/routes/leady_logs.py
# all call storage_paths.platform_logs_db_path() at call time instead of
# caching their own path constant at import time, so redirecting that ONE
# function redirects all three at once (this used to require patching three
# independent module attributes -- see git history of this fixture).
# ---------------------------------------------------------------------------
@pytest.fixture(scope="session", autouse=True)
def _isolate_real_log_and_platform_log_files(tmp_path_factory):
    import logging

    from modules.core import storage_paths

    # logs/error.log is attached to the ROOT logger by modules/core/request_logging.py;
    # access.log / access_errors.log / login_attempts.log are attached to
    # three named loggers. Detach + stop propagation so nothing this session
    # logs can reach those real files, regardless of level.
    for logger in [logging.getLogger()] + [logging.getLogger(name) for name in ("access", "access_errors", "login")]:
        for handler in list(logger.handlers):
            logger.removeHandler(handler)
            handler.close()

    for name in ("access", "access_errors", "login"):
        logger = logging.getLogger(name)
        logger.propagate = False

    # create_app() attaches those file handlers via configure_logging() (no
    # longer at import time). In-process tests share one interpreter whose
    # storage root is the real checkout, so keep it a no-op here; handler
    # placement is covered by the subprocess entry-point tests.
    import modules.core.app_factory as app_factory

    app_factory.configure_logging = lambda: None

    # logs/platform/platform_logs.db: redirect the single central resolver
    # function for the whole session (no revert needed -- the process exits
    # after the test run).
    tmp_dir = tmp_path_factory.mktemp("isolated_platform_logs")
    isolated_db_path = tmp_dir / "platform_logs.db"
    storage_paths.platform_logs_dir = lambda: tmp_dir
    storage_paths.platform_logs_db_path = lambda: isolated_db_path

    yield


# ---------------------------------------------------------------------------
# Session-wide safety guard: confirm the storage contract suite (and the
# rest of the suite) never touches the real runtime directories it exists to
# protect. Snapshot cheap signals (entry count + max mtime, not full file
# hashes) before the session and compare after.
# ---------------------------------------------------------------------------
_GUARDED_REAL_PATHS = (
    "instances",
    os.path.join("static", "images"),
    "logs",
    os.path.join("InvestmentManager", "alerts"),
    os.path.join("InvestmentManager", "knowledge_center"),
)


def _snapshot_dir(path: Path):
    if not path.is_dir():
        return None
    entries = list(path.iterdir())
    max_mtime = max((p.stat().st_mtime for p in entries), default=0.0)
    return (len(entries), max_mtime)


@pytest.fixture(scope="session", autouse=True)
def _real_runtime_dirs_untouched_by_test_suite():
    before = {rel: _snapshot_dir(PROJECT_ROOT / rel) for rel in _GUARDED_REAL_PATHS}
    yield
    after = {rel: _snapshot_dir(PROJECT_ROOT / rel) for rel in _GUARDED_REAL_PATHS}
    changed = {rel: (before[rel], after[rel]) for rel in _GUARDED_REAL_PATHS if before[rel] != after[rel]}
    assert not changed, (
        "Test suite modified real runtime directories it must never touch: "
        f"{changed}"
    )


@pytest.fixture()
def app():
    """A Flask app built from the real, unmodified create_app() factory."""
    application = create_app()
    application.config.update(TESTING=True)
    # Flask-Limiter's memory:// storage is a process-wide singleton shared by
    # every app instance; leaving it enabled would let unrelated tests consume
    # each other's per-IP quotas. Toggle the singleton off here (test isolation
    # only -- real dev/prod keep limiting on; RATELIMIT_ENABLED in app.config is
    # read at init_app time, so the runtime `enabled` flag is what takes effect
    # after create_app). Focused A4 limiter tests re-enable and reset per test.
    from modules.core.extensions import limiter

    _prev_enabled = limiter.enabled
    limiter.enabled = False
    yield application
    limiter.enabled = _prev_enabled


@pytest.fixture()
def app_context(app):
    with app.app_context():
        yield app


@pytest.fixture()
def request_context(app):
    """A request context (not just app context).

    Needed for code that calls url_for() without SERVER_NAME configured,
    e.g. modules.investment.functions.get_image_path(). An app_context
    alone is not sufficient for that (Flask raises RuntimeError).
    """
    with app.test_request_context():
        yield app


@pytest.fixture()
def client(app):
    return app.test_client()


@pytest.hookimpl(tryfirst=True)
def pytest_configure(config):
    if config.option.basetemp is None:
        config.option.basetemp = str(Path(_IMPORT_TIME_RUNTIME.name) / "pytest")
    # pytest's own cache must not write into the working checkout either.
    config._inicache["cache_dir"] = str(Path(_IMPORT_TIME_RUNTIME.name) / "pytest-cache")
    config.addinivalue_line("markers", "crm_session_guard: run the real CRM session revalidation (middleware/session_guard.py)")


@pytest.fixture(autouse=True)
def _legacy_tests_skip_crm_session_revalidation(request, monkeypatch):
    """The CRM revalidates every session against agents.db (session_guard.check_session). Older tests plant a session by hand
    (user_id / access_level only, often without any agents.db) - that is a test setup shortcut, not a login. They keep it
    here; every test that uses the `crm_env` fixture (real agents.db + real login) or the `crm_session_guard` marker runs
    the real guard. The guard itself is covered by tests/investmentmanager/test_session_lifecycle.py."""
    if "crm_env" in request.fixturenames or request.node.get_closest_marker("crm_session_guard"):
        return
    from InvestmentManager.middleware import session_guard
    monkeypatch.setattr(session_guard, "check_session", lambda: None)


@pytest.fixture(autouse=True)
def _executor_never_reads_the_real_dotenv(tmp_path_factory, monkeypatch):
    """The export executor reads the application's .env itself; tests must never see a developer's real credentials."""
    from InvestmentManager.integrator import export_transport_config
    monkeypatch.setattr(export_transport_config, "ENV_FILE", tmp_path_factory.getbasetemp() / "no-such-dotenv")
    yield


@pytest.fixture(autouse=True)
def _test_safety_violations():
    before = len(safety.VIOLATIONS)
    yield
    assert safety.VIOLATIONS[before:] == [], "Test swallowed a safety boundary violation"


def pytest_sessionfinish(session, exitstatus):
    if safety.VIOLATIONS:
        session.exitstatus = pytest.ExitCode.TESTS_FAILED
