"""Tests for pattern tracking."""
import pytest
from greymatter_core.db import SQLiteDatabase
from greymatter_core.patterns import PatternManager


@pytest.fixture
def db():
    return SQLiteDatabase(":memory:")


@pytest.fixture
def patterns(db):
    return PatternManager(db)


def test_create_pattern(patterns):
    p = patterns.create(type="process", domain="testing", title="TDD First",
                        observation="Always write tests before implementation")
    assert p["id"].startswith("pat-")
    assert p["title"] == "TDD First"
    assert p["confidence"] == "low"


def test_get_pattern(patterns):
    created = patterns.create(type="process", domain="testing", title="Test",
                              observation="Observation")
    fetched = patterns.get(created["id"])
    assert fetched is not None
    assert fetched["title"] == "Test"


def test_get_nonexistent(patterns):
    assert patterns.get("pat-nonexistent") is None


def test_search_by_domain(patterns):
    patterns.create(type="process", domain="testing", title="A", observation="A")
    patterns.create(type="process", domain="coding", title="B", observation="B")
    results = patterns.search(domain="testing")
    assert len(results) == 1
    assert results[0]["title"] == "A"


def test_search_by_min_confidence(patterns):
    p = patterns.create(type="process", domain="testing", title="A", observation="A")
    # Low confidence pattern should not appear in medium+ search
    results = patterns.search(min_confidence="medium")
    assert len(results) == 0
    results = patterns.search(min_confidence="low")
    assert len(results) == 1


def test_confidence_escalation(patterns, db):
    p = patterns.create(type="process", domain="testing", title="A", observation="A")
    # Add 3 confirmed evidence — should escalate to medium
    for i in range(3):
        patterns.add_evidence(p["id"], session_id=f"s-{i}")
    updated = patterns.get(p["id"])
    assert updated["confidence"] == "medium"


def test_list_all(patterns):
    patterns.create(type="process", domain="testing", title="A", observation="A")
    patterns.create(type="style", domain="coding", title="B", observation="B")
    all_patterns = patterns.list_all()
    assert len(all_patterns) == 2


def test_confirmations_column_updated(patterns):
    p = patterns.create(type="process", domain="testing", title="A", observation="A")
    patterns.add_evidence(p["id"], session_id="s-1")
    patterns.add_evidence(p["id"], session_id="s-2")
    updated = patterns.get(p["id"])
    assert updated["confirmations"] == 2


def test_delete_pattern(patterns):
    p = patterns.create(type="process", domain="testing", title="A", observation="A")
    assert patterns.delete(p["id"]) is True
    assert patterns.get(p["id"]) is None
    assert patterns.delete("pat-nonexistent") is False
