"""Tests for abreka.text_match — word-boundary and regex search."""

from __future__ import annotations

import pytest

from abreka.text_match import parse_query, text_match


class TestParseQuery:
    def test_plain_query_becomes_word_boundary(self):
        pattern = parse_query("SAM")
        assert pattern.search("SAM is great")
        assert not pattern.search("SAME thing")

    def test_plain_query_case_insensitive(self):
        pattern = parse_query("sam")
        assert pattern.search("SAM is great")
        assert pattern.search("sam is great")

    def test_regex_syntax(self):
        pattern = parse_query("/SAM/")
        # Regex: literal SAM, case-sensitive
        assert pattern.search("SAM here")
        assert pattern.search("SAME here")  # no word boundary in regex mode
        assert not pattern.search("sam here")  # case-sensitive

    def test_regex_case_insensitive_flag(self):
        pattern = parse_query("/sam/i")
        assert pattern.search("SAM here")
        assert pattern.search("sam here")
        assert pattern.search("SAME")

    def test_regex_dot_star(self):
        pattern = parse_query("/CNN.*attention/i")
        assert pattern.search("CNN with attention mechanism")
        assert not pattern.search("attention with CNN")  # order matters

    def test_plain_query_special_chars_escaped(self):
        """Special regex chars in plain queries should be escaped."""
        pattern = parse_query("C++")
        assert pattern.search("using C++ here")
        assert not pattern.search("using C here")

    def test_plain_query_word_boundary_at_edges(self):
        pattern = parse_query("SAM")
        assert pattern.search("SAM")
        assert pattern.search("use SAM model")
        assert not pattern.search("SAMPLE")
        assert not pattern.search("EXSAM")

    def test_empty_query_matches_everything(self):
        pattern = parse_query("")
        assert pattern.search("anything")
        assert pattern.search("")

    def test_regex_invalid_raises(self):
        with pytest.raises(ValueError, match="Invalid regex"):
            parse_query("/[unclosed/")


class TestTextMatch:
    def test_match_in_any_field(self):
        assert text_match("CNN", "Baseline CNN model", "Train CNN")
        assert text_match("CNN", "No match here", "But CNN here")
        assert not text_match("CNN", "No match", "Nothing")

    def test_regex_match(self):
        assert text_match("/^Baseline/", "Baseline CNN model", "method")
        assert not text_match("/^Baseline/", "A Baseline model", "method")

    def test_no_fields(self):
        assert not text_match("CNN")

    def test_empty_query(self):
        assert text_match("", "anything", "else")
