"""Tests for PR flakiness reviewer pattern matching."""

import re

import pytest


class TestMissingAwaitPattern:
    """Verify the missing_await regex matches all expected forms."""

    @pytest.fixture
    def pattern(self):
        from api.ai.pr_reviewer import FLAKY_PATTERNS

        for p in FLAKY_PATTERNS:
            if p["name"] == "missing_await":
                return re.compile(p["pattern"])
        raise AssertionError("missing_await pattern not found")

    def test_matches_plain_fetch(self, pattern):
        """Plain fetch(url) should be detected."""
        assert pattern.search("fetch('https://api.example.com')")

    def test_matches_fetch_method(self, pattern):
        """fetchData(...) should be detected."""
        assert pattern.search("fetchData(someUrl)")

    def test_matches_axios_get(self, pattern):
        """axios.get(...) should be detected."""
        assert pattern.search("axios.get('/api/users')")

    def test_matches_httpx_post(self, pattern):
        """httpx.post(...) should be detected."""
        assert pattern.search("httpx.post(url, json=data)")

    def test_no_match_when_awaited(self, pattern):
        """await fetch(...) should NOT match."""
        assert not pattern.search("await fetch('https://api.example.com')")

    def test_no_match_await_axios(self, pattern):
        """await axios.get(...) should NOT match."""
        assert not pattern.search("await axios.get('/api')")


class TestUnorderedSqlPattern:
    """Verify the unordered_sql regex doesn't cause ReDoS."""

    @pytest.fixture
    def pattern(self):
        from api.ai.pr_reviewer import FLAKY_PATTERNS

        for p in FLAKY_PATTERNS:
            if p["name"] == "unordered_sql":
                return re.compile(p["pattern"])
        raise AssertionError("unordered_sql pattern not found")

    def test_matches_select_without_order_by(self, pattern):
        assert pattern.search("SELECT id, name FROM users")

    def test_matches_select_from_even_with_trailing_order_by(self, pattern):
        """Pattern is a heuristic — ORDER BY after FROM still matches the SELECT...FROM span."""
        assert pattern.search("SELECT id, name FROM users ORDER BY id")

    def test_long_input_completes_quickly(self, pattern):
        """Regression test: long input should not cause catastrophic backtracking."""
        import time

        long_input = "SELECT " + ", ".join(f"col{i}" for i in range(200)) + " FROM big_table"
        start = time.monotonic()
        pattern.search(long_input)
        elapsed = time.monotonic() - start
        assert elapsed < 1.0, f"Regex took {elapsed:.2f}s — possible ReDoS"
