"""Tests for work item management."""
import pytest
from greymatter_core.db import SQLiteDatabase
from greymatter_core.work_items import WorkItemManager


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


@pytest.fixture
def work(db):
    return WorkItemManager(db)


def test_create_work_item(work):
    item = work.create(title="Build login page", description="OAuth2 login flow")
    assert item["id"].startswith("wi-")
    assert item["status"] == "queued"
    assert item["priority"] == 100


def test_list_by_status(work):
    work.create(title="A")
    item_b = work.create(title="B")
    work.update_status(item_b["id"], "in_progress")
    queued = work.list(status="queued")
    assert len(queued) == 1
    assert queued[0]["title"] == "A"
    in_progress = work.list(status="in_progress")
    assert len(in_progress) == 1
    assert in_progress[0]["title"] == "B"


def test_complete_work_item(work):
    item = work.create(title="Do thing")
    work.complete(item["id"])
    completed = work.get(item["id"])
    assert completed["status"] == "completed"
    assert completed["completed_at"] is not None


def test_priority_ordering(work):
    work.create(title="Low priority", priority=200)
    work.create(title="High priority", priority=10)
    items = work.list()
    assert items[0]["title"] == "High priority"
    assert items[1]["title"] == "Low priority"


def test_get_existing_item(work):
    created = work.create(
        title="Build auth service",
        description="Implement OAuth2 flow",
        priority=50,
        domain_tags="auth,security",
        project="greymatter",
        feature="auth",
    )
    item_id = created["id"]
    result = work.get(item_id)
    assert result is not None
    assert result["id"] == item_id
    assert result["title"] == "Build auth service"
    assert result["description"] == "Implement OAuth2 flow"
    assert result["priority"] == 50
    assert result["domain_tags"] == "auth,security"
    assert result["project"] == "greymatter"
    assert result["feature"] == "auth"
    assert result["type"] == "task"
    assert result["status"] == "queued"
    assert result["short_id"] == item_id[-4:]
    assert result["created_at"] is not None
    assert result["completed_at"] is None


def test_get_nonexistent(work):
    assert work.get("wi-nonexistent") is None


def test_update_to_pending_review(work):
    item = work.create(title="Implement login")
    work.update_status(item["id"], "in_progress")
    result = work.update_status(item["id"], "pending_review")
    assert result["status"] == "pending_review"


def test_update_to_needs_revision(work):
    item = work.create(title="Implement login")
    work.update_status(item["id"], "pending_review")
    result = work.update_status(item["id"], "needs_revision")
    assert result["status"] == "needs_revision"


def test_update_to_approved(work):
    item = work.create(title="Implement login")
    work.update_status(item["id"], "pending_review")
    result = work.update_status(item["id"], "approved")
    assert result["status"] == "approved"


def test_update_review_notes(work):
    item = work.create(title="Implement login")
    work.update_status(item["id"], "pending_review")
    result = work.update_review(item["id"], "needs_revision", "Missing error handling for 401")
    assert result["status"] == "needs_revision"
    assert result["review_notes"] == "Missing error handling for 401"


def test_update_review_notes_nonexistent(work):
    result = work.update_review("wi-nonexistent", "approved", "LGTM")
    assert result is None


def test_list_pending_review(work):
    a = work.create(title="A")
    b = work.create(title="B")
    work.update_status(a["id"], "pending_review")
    work.update_status(b["id"], "in_progress")
    pending = work.list(status="pending_review")
    assert len(pending) == 1
    assert pending[0]["title"] == "A"


# --- completed_since ---


def test_completed_since_returns_recent(work):
    """completed_since returns items completed within the time window."""
    item = work.create(title="Done task")
    work.complete(item["id"], result_summary="3 files changed, commit abc1234")
    results = work.completed_since(hours=24)
    assert len(results) == 1
    assert results[0]["id"] == item["id"]
    assert results[0]["status"] == "completed"
    assert results[0]["result_summary"] == "3 files changed, commit abc1234"


def test_completed_since_excludes_non_completed(work):
    """completed_since does not return queued or in-progress items."""
    a = work.create(title="Still queued")
    b = work.create(title="In progress")
    work.update_status(b["id"], "in_progress")
    c = work.create(title="Actually done")
    work.complete(c["id"])
    results = work.completed_since(hours=24)
    assert len(results) == 1
    assert results[0]["title"] == "Actually done"


def test_completed_since_empty_when_none(work):
    """completed_since returns empty list when nothing is completed."""
    work.create(title="Pending task")
    results = work.completed_since(hours=24)
    assert results == []


def test_completed_since_respects_limit(work):
    """completed_since respects the limit parameter."""
    for i in range(5):
        item = work.create(title=f"Task {i}")
        work.complete(item["id"])
    results = work.completed_since(hours=24, limit=3)
    assert len(results) == 3


def test_completed_since_orders_most_recent_first(work):
    """completed_since returns most recently completed items first."""
    first = work.create(title="First done")
    work.complete(first["id"])
    second = work.create(title="Second done")
    work.complete(second["id"])
    results = work.completed_since(hours=24)
    assert len(results) == 2
    # Most recent first
    assert results[0]["title"] == "Second done"
    assert results[1]["title"] == "First done"


def test_complete_with_result_summary(work):
    """complete() stores the result_summary text."""
    item = work.create(title="Summarized task")
    work.complete(item["id"], result_summary="5 files, commit deadbeef")
    result = work.get(item["id"])
    assert result["result_summary"] == "5 files, commit deadbeef"
    assert result["completed_at"] is not None


def test_complete_without_result_summary(work):
    """complete() works without a result_summary (defaults to None)."""
    item = work.create(title="No summary task")
    work.complete(item["id"])
    result = work.get(item["id"])
    assert result["result_summary"] is None
    assert result["status"] == "completed"
