"""Tests for quality standards manager."""
import json
import pytest
from greymatter_core.db import SQLiteDatabase
from greymatter_core.standards import StandardsManager


@pytest.fixture
def db():
    database = SQLiteDatabase(":memory:")
    yield database
    database.close()


@pytest.fixture
def standards(db):
    return StandardsManager(db)


def test_create_standard(standards):
    s = standards.create(
        standard_id="qs-typing-protocol",
        category="typing",
        rule="Use Protocol types, not concrete implementations",
        severity="critical",
        rationale="Enables swapping implementations without changing callers",
    )
    assert s["id"] == "qs-typing-protocol"
    assert s["category"] == "typing"
    assert s["active"] == 1


def test_get_active_standards(standards):
    standards.create(standard_id="qs-a", category="typing", rule="Rule A", severity="critical")
    standards.create(standard_id="qs-b", category="sql", rule="Rule B", severity="important")
    standards.create(standard_id="qs-c", category="naming", rule="Rule C", severity="minor")
    active = standards.get_active()
    assert len(active) == 3


def test_get_active_by_severity(standards):
    standards.create(standard_id="qs-a", category="typing", rule="Rule A", severity="critical")
    standards.create(standard_id="qs-b", category="sql", rule="Rule B", severity="minor")
    critical = standards.get_active(severity_filter=["critical"])
    assert len(critical) == 1
    assert critical[0]["severity"] == "critical"


def test_deactivate_standard(standards):
    standards.create(standard_id="qs-a", category="typing", rule="Rule A", severity="critical")
    standards.deactivate("qs-a")
    active = standards.get_active()
    assert len(active) == 0


def test_context_payload_is_compact_json(standards):
    standards.create(standard_id="qs-a", category="typing", rule="Rule A", severity="critical")
    standards.create(standard_id="qs-b", category="sql", rule="Rule B", severity="important")
    payload = standards.get_context_payload()
    parsed = json.loads(payload)
    assert len(parsed) == 2
    assert all("category" in item and "rule" in item for item in parsed)


def test_seed_defaults(standards):
    count = standards.seed_defaults()
    assert count >= 10
    active = standards.get_active()
    assert len(active) >= 10


def test_seed_defaults_idempotent(standards):
    count1 = standards.seed_defaults()
    count2 = standards.seed_defaults()
    assert count2 == 0  # no new standards created on second call
