"""Tests for benchmarking manager."""
import pytest
from greymatter_core.db import SQLiteDatabase
from greymatter_core.benchmarks import BenchmarkManager


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


@pytest.fixture
def benchmarks(db):
    return BenchmarkManager(db)


def _seed_standard(db, standard_id="qs-typing-protocol"):
    """Helper to seed a quality standard for scoring tests."""
    db.execute(
        """INSERT INTO quality_standards (id, category, rule, severity)
           VALUES (?, 'typing', 'Test rule', 'critical')""",
        (standard_id,),
    )


def test_start_and_complete_run(benchmarks):
    run = benchmarks.start_run(approach="subagent", task_name="Task 2: Database")
    assert run["id"].startswith("br-")
    assert run["approach"] == "subagent"
    assert run["completed_at"] is None

    completed = benchmarks.complete_run(
        run["id"], lines=174, tests=6, passing=6, first_pass=True
    )
    assert completed["completed_at"] is not None
    assert completed["lines_written"] == 174
    assert completed["first_pass_success"] == 1


def test_score_run(benchmarks, db):
    _seed_standard(db, "qs-typing-protocol")
    _seed_standard(db, "qs-sql-no-interpolation")
    run = benchmarks.start_run(approach="subagent", task_name="Task 6")
    benchmarks.score_run(
        run["id"], "qs-typing-protocol", passed=False,
        detail="Used SQLiteDatabase instead of Database Protocol",
        found_by="code_review",
    )
    benchmarks.score_run(
        run["id"], "qs-sql-no-interpolation", passed=True,
        detail=None, found_by="code_review",
    )
    scores = benchmarks.get_scores(run["id"])
    assert len(scores) == 2
    assert scores[0]["passed"] == 0
    assert scores[1]["passed"] == 1


def test_record_and_resolve_issue(benchmarks):
    run = benchmarks.start_run(approach="subagent", task_name="Task 4")
    issue_id = benchmarks.record_issue(
        run["id"], severity="critical", category="ids",
        description="3-char IDs have collision risk", found_by="greymatter_review",
    )
    assert issue_id > 0

    benchmarks.resolve_issue(issue_id, fix_minutes=5)
    issues = benchmarks.get_issues(run["id"])
    assert issues[0]["fixed_at"] is not None
    assert issues[0]["time_to_fix_minutes"] == 5


def test_defect_density(benchmarks):
    run1 = benchmarks.start_run(approach="greymatter", task_name="GM Task")
    benchmarks.complete_run(run1["id"], lines=200, tests=10, passing=10, first_pass=True)
    benchmarks.record_issue(run1["id"], "minor", "naming", "Bad name", "code_review")

    run2 = benchmarks.start_run(approach="subagent", task_name="Sub Task")
    benchmarks.complete_run(run2["id"], lines=200, tests=10, passing=10, first_pass=True)
    benchmarks.record_issue(run2["id"], "critical", "typing", "Wrong type", "code_review")
    benchmarks.record_issue(run2["id"], "important", "sql", "Bad SQL", "code_review")
    benchmarks.record_issue(run2["id"], "minor", "naming", "Bad name", "code_review")

    density = benchmarks.defect_density()
    gm = next(d for d in density if d["approach"] == "greymatter")
    sub = next(d for d in density if d["approach"] == "subagent")
    assert gm["defects_per_kloc"] < sub["defects_per_kloc"]


def test_first_pass_quality(benchmarks, db):
    _seed_standard(db, "qs-typing-protocol")
    _seed_standard(db, "qs-sql-no-interpolation")
    run = benchmarks.start_run(approach="subagent", task_name="Test")
    benchmarks.score_run(run["id"], "qs-typing-protocol", passed=True, found_by="review")
    benchmarks.score_run(run["id"], "qs-sql-no-interpolation", passed=False, found_by="review")
    result = benchmarks.first_pass_quality()
    assert len(result) == 1
    assert result[0]["first_pass_pct"] == 50.0


def test_summary(benchmarks, db):
    _seed_standard(db, "qs-typing-protocol")
    run = benchmarks.start_run(approach="subagent", task_name="Test")
    benchmarks.complete_run(run["id"], lines=100, tests=5, passing=5, first_pass=True)
    benchmarks.record_issue(run["id"], "critical", "typing", "Issue", "review")
    benchmarks.score_run(run["id"], "qs-typing-protocol", passed=False, found_by="review")

    summary = benchmarks.summary()
    assert len(summary) > 0
    assert "approach" in summary[0]
