"""Wave A4: authentication rate limiting, constant-time DB Shell comparison,
and dedicated-logger isolation.

All runtime lives under a temporary DATA_DIR; the developer's real
InvestmentData is never touched. Rate-limit tests re-enable the Flask-Limiter
singleton (the shared `app` fixture disables it) and reset its storage per
test so they never depend on wall-clock delays or external storage.
"""
import contextlib
import json
import logging
import sqlite3
import subprocess
import sys
import tempfile
from pathlib import Path

import pytest
from werkzeug.security import generate_password_hash

from modules.core.extensions import limiter

REPO_ROOT = Path(__file__).resolve().parents[2]


def _seed_agents_db(data_dir, *, password="s3cr3t-value"):
    db = data_dir / "databases" / "agents.db"
    db.parent.mkdir(parents=True, exist_ok=True)
    with sqlite3.connect(db) as conn:
        conn.execute(
            "CREATE TABLE agents_v2 (id INTEGER PRIMARY KEY, login TEXT, password_hash TEXT, "
            "first_name TEXT, last_name TEXT, email TEXT, phone TEXT, license TEXT, "
            "access_level TEXT, is_active INTEGER)"
        )
        conn.execute(
            "INSERT INTO agents_v2 VALUES (1, 'boss.master', ?, 'Boss', 'Master', '', '', '', 'master', 1)",
            (generate_password_hash(password),),
        )
    sqlite3.connect(data_dir / "databases" / "IDB.db").close()


@contextlib.contextmanager
def _limiter_on():
    """Turn the process-wide Flask-Limiter singleton ON with a clean storage and give it back EXACTLY as it was.

    The singleton's `enabled` flag is read by every later `create_app()` (Flask-Limiter registers its before/after_request gates only for an
    enabled limiter), so a test that leaves it disabled silently changes the gates of the apps built after it - which the K8 route-policy
    snapshot then reports as drift (see test_the_limiter_singleton_is_restored_...)."""
    previous = limiter.enabled
    limiter.enabled = True
    limiter.reset()
    try:
        yield
    finally:
        limiter.reset()
        limiter.enabled = previous


@pytest.fixture()
def limited_client(tmp_path, monkeypatch):
    """A client with the limiter turned ON and storage reset (opposite of the
    default `app` fixture, which disables it)."""
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    monkeypatch.setenv("DB_SHELL_PASSWORD", "unlock-secret")
    _seed_agents_db(tmp_path)

    from modules.core.app_factory import create_app

    application = create_app()
    application.config.update(TESTING=True)
    with _limiter_on():
        yield application.test_client()


def _limiter_gates(application):
    names = []
    for function in application.before_request_funcs.get(None, []) + application.after_request_funcs.get(None, []):
        function = getattr(function, "func", function)
        names.append(getattr(function, "__qualname__", repr(function)))
    return sorted(name for name in names if "Limiter" in name)


def test_the_limiter_singleton_is_restored_so_later_apps_keep_their_limiter_gates(tmp_path, monkeypatch):
    """Isolation guard for the K8 snapshot: no test may leave the shared limiter disabled for the apps built after it.

    Minimal one-process reproducer of the old defect: a test that ended with `limiter.enabled = False` made every later `create_app()`
    come up WITHOUT the Flask-Limiter before/after_request gates (RATELIMIT_ENABLED=False is taken from the singleton)."""
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    from modules.core.app_factory import create_app

    assert limiter.enabled is True, "an earlier test left the shared limiter disabled (restore it instead of forcing False)"
    healthy = create_app()                                                # (the limiter needs an initialised app before it can be reset)
    assert _limiter_gates(healthy) == ["Limiter.__inject_headers", "Limiter._check_request_limit"]
    with _limiter_on():
        assert limiter.enabled is True
    assert limiter.enabled is True                                        # given back as it was
    try:
        limiter.enabled = False                                           # what the old fixture teardown left behind
        broken = create_app()
        assert _limiter_gates(broken) == [] and broken.config["RATELIMIT_ENABLED"] is False
    finally:
        limiter.enabled = True


# ---------------------------------------------------------------------------
# CRM login rate limit  (10/min; 100/hour, POST only)
# ---------------------------------------------------------------------------

class TestLoginRateLimit:
    def test_ten_posts_allowed_then_eleventh_is_429(self, limited_client):
        statuses = [limited_client.post("/crm/", data={"username": "x", "password": "y"}).status_code for _ in range(11)]
        assert statuses[:10] == [200] * 10  # failed logins re-render the page (200)
        assert statuses[10] == 429

    def test_get_login_page_does_not_consume_the_post_quota(self, limited_client):
        for _ in range(15):
            assert limited_client.get("/crm/").status_code == 200
        # POSTs still have their full quota afterwards.
        assert limited_client.post("/crm/", data={"username": "x", "password": "y"}).status_code == 200

    def test_successful_login_works_while_under_the_limit(self, limited_client):
        resp = limited_client.post("/crm/", data={"username": "boss.master", "password": "s3cr3t-value"})
        assert resp.status_code == 302
        assert resp.headers["Location"].endswith("/crm/dashboard")

    def test_both_login_limit_windows_are_declared(self):
        import inspect

        from InvestmentManager import main as login_module

        source = inspect.getsource(login_module)
        assert 'limiter.limit("10 per minute; 100 per hour"' in source
        assert "methods=['POST']" in source


# ---------------------------------------------------------------------------
# DB Shell unlock rate limit  (5/min) + constant-time comparison
# ---------------------------------------------------------------------------

class TestDbShellRateLimitAndComparison:
    def _as_master(self, client):
        with client.session_transaction() as sess:
            sess.update(user_id=1, access_level="master", first_name="Boss", last_name="Master")

    def test_five_attempts_then_sixth_is_429(self, limited_client):
        self._as_master(limited_client)
        statuses = [limited_client.post("/crm/dbshell/unlock", json={"password": "wrong"}).status_code for _ in range(6)]
        assert statuses[:5] == [401] * 5
        assert statuses[5] == 429

    def test_correct_password_unlocks_while_under_limit(self, limited_client):
        self._as_master(limited_client)
        resp = limited_client.post("/crm/dbshell/unlock", json={"password": "unlock-secret"})
        assert resp.status_code == 200
        assert resp.get_json()["success"] is True
        with limited_client.session_transaction() as sess:
            assert "db_shell_unlocked_at" in sess

    @pytest.mark.parametrize("bad", ["wrong", "unlock", "unlock-secretX", "Unlock-secret", "unlock-secre"])
    def test_wrong_prefix_suffix_altered_all_401(self, limited_client, bad):
        self._as_master(limited_client)
        resp = limited_client.post("/crm/dbshell/unlock", json={"password": bad})
        assert resp.status_code == 401
        with limited_client.session_transaction() as sess:
            assert "db_shell_unlocked_at" not in sess

    def test_login_and_dbshell_limits_do_not_share_counters(self, limited_client):
        self._as_master(limited_client)
        # Exhaust the dbshell limit (5).
        for _ in range(6):
            limited_client.post("/crm/dbshell/unlock", json={"password": "wrong"})
        # Login still has its own, separate quota.
        assert limited_client.post("/crm/", data={"username": "x", "password": "y"}).status_code == 200

    def test_unlock_uses_constant_time_comparison(self):
        # compare_digest is itself the A4 security requirement.
        import inspect

        from InvestmentManager.routes import dbshell

        source = inspect.getsource(dbshell.dbshell_unlock)
        assert "hmac.compare_digest" in source
        assert "!= expected_password" not in source


def test_platform_lead_limit_unchanged():
    import inspect

    from InvestmentWebsite.blueprints.platform import platform

    assert '@limiter.limit("3 per minute")' in inspect.getsource(platform.platform_send_lead) or \
        "3 per minute" in inspect.getsource(platform.platform_send_lead)


def test_no_global_default_limit_introduced():
    import inspect

    from modules.core import extensions

    assert "default_limits=[]" in inspect.getsource(extensions)


# ---------------------------------------------------------------------------
# Logging isolation -- runs in a subprocess so a fresh interpreter observes
# handler wiring without this session's conftest log-detach fixture.
# ---------------------------------------------------------------------------

_LOG_PROBE = '''\
import io, json, logging, os, sys, contextlib
from pathlib import Path

sys.path.insert(0, {repo!r})
os.environ["DATA_DIR"] = {data!r}
os.environ["FLASK_ENV"] = "development"
os.environ["SECRET_KEY"] = "a4log"

result = {{}}

# import-only must not create logs/
import modules.core.request_logging as ml
result["import_created_logs_dir"] = os.path.isdir(os.path.join({data!r}, "logs"))

from modules.core.app_factory import create_app

err = io.StringIO()
with contextlib.redirect_stderr(err):
    app = create_app()
    # handler counts after first create_app
    def hcount():
        return {{name or "root": len(logging.getLogger(name).handlers) for name in ("", "access", "access_errors", "login")}}
    result["handlers_after_1"] = hcount()
    create_app()  # second app, same process
    result["handlers_after_2"] = hcount()

    logging.getLogger("access").info(json.dumps({{"probe": "ACCESS_REC"}}))
    logging.getLogger("access_errors").info(json.dumps({{"probe": "ACCESSERR_REC"}}))
    logging.getLogger("login").info("LOGIN_REC")
    logging.getLogger().error("ROOT_ERROR_REC")
    for h in logging.getLogger().handlers + logging.getLogger("access").handlers:
        try: h.flush()
        except Exception: pass

result["stderr"] = err.getvalue()
result["propagate"] = {{name: logging.getLogger(name).propagate for name in ("access", "access_errors", "login")}}

data = Path({data!r})
def read(p):
    f = data / p
    return f.read_text(encoding="utf-8", errors="replace") if f.exists() else ""

result["access_log"] = read("logs/website/access.log")
result["access_errors_log"] = read("logs/website/access_errors.log")
result["login_log"] = read("logs/website/login_attempts.log")
result["error_log"] = read("logs/error.log")
print("PROBE " + json.dumps(result))
'''


@pytest.fixture(scope="module")
def log_probe():
    with tempfile.TemporaryDirectory() as data_dir:
        script = _LOG_PROBE.format(repo=str(REPO_ROOT), data=data_dir)
        with tempfile.TemporaryDirectory() as script_dir:
            script_path = Path(script_dir) / "probe_logging.py"
            script_path.write_text(script, encoding="utf-8")
            completed = subprocess.run(
                [sys.executable, str(script_path)],
                cwd=script_dir,
                capture_output=True,
                text=True,
                timeout=120,
            )
        line = [l for l in completed.stdout.splitlines() if l.startswith("PROBE ")]
        assert line, f"probe failed rc={completed.returncode}\n{completed.stderr}"
        return json.loads(line[-1][len("PROBE "):])


def test_import_alone_creates_no_log_directory(log_probe):
    assert log_probe["import_created_logs_dir"] is False


def test_dedicated_loggers_do_not_propagate(log_probe):
    assert log_probe["propagate"] == {"access": False, "access_errors": False, "login": False}


def test_access_record_only_in_access_log(log_probe):
    assert "ACCESS_REC" in log_probe["access_log"]
    assert "ACCESS_REC" not in log_probe["error_log"]
    assert "ACCESS_REC" not in log_probe["stderr"]


def test_access_error_record_only_in_access_errors_log(log_probe):
    assert "ACCESSERR_REC" in log_probe["access_errors_log"]
    assert "ACCESSERR_REC" not in log_probe["error_log"]
    assert "ACCESSERR_REC" not in log_probe["stderr"]


def test_login_record_only_in_login_log(log_probe):
    assert "LOGIN_REC" in log_probe["login_log"]
    assert "LOGIN_REC" not in log_probe["error_log"]
    assert "LOGIN_REC" not in log_probe["stderr"]


def test_root_error_record_still_reaches_error_log(log_probe):
    assert "ROOT_ERROR_REC" in log_probe["error_log"]


def test_repeated_create_app_does_not_duplicate_handlers(log_probe):
    assert log_probe["handlers_after_1"] == log_probe["handlers_after_2"]
    assert log_probe["handlers_after_1"]["access"] == 1
    assert log_probe["handlers_after_1"]["login"] == 1
