"""Tests for parallelism optimization (Phase 7, Stream D)."""

import pytest

from loom.graph.store import get_ready_count, create_task, create_tasks_batch, complete_task, claim_task
from loom.graph.task import Task, TaskStatus, Priority
from loom.ids import task_id as gen_task_id


class TestGetReadyCount:
    async def test_no_tasks(self, pool, project):
        """Empty project should have 0 ready tasks."""
        count = await get_ready_count(pool, project)
        assert count == 0

    async def test_one_pending_no_deps(self, pool, project):
        """Single pending task with no deps should be counted."""
        task = Task(
            id=gen_task_id(), project_id=project,
            title="Task 1", status=TaskStatus.PENDING,
            priority=Priority.P1,
        )
        await create_task(pool, task)
        count = await get_ready_count(pool, project)
        assert count == 1

    async def test_multiple_ready(self, pool, project):
        """Multiple pending tasks with no deps should all count."""
        tasks = [
            Task(
                id=gen_task_id(), project_id=project,
                title=f"Task {i}", status=TaskStatus.PENDING,
                priority=Priority.P1,
            )
            for i in range(5)
        ]
        await create_tasks_batch(pool, tasks)
        count = await get_ready_count(pool, project)
        assert count == 5

    async def test_blocked_not_counted(self, pool, project):
        """Task with unmet deps should not be counted."""
        t1 = Task(
            id=gen_task_id(), project_id=project,
            title="Parent", status=TaskStatus.PENDING,
            priority=Priority.P1,
        )
        t2 = Task(
            id=gen_task_id(), project_id=project,
            title="Child", status=TaskStatus.BLOCKED,
            priority=Priority.P1,
            depends_on=[t1.id],
        )
        await create_tasks_batch(pool, [t1, t2])
        count = await get_ready_count(pool, project)
        assert count == 1  # only t1

    async def test_deps_done_makes_ready(self, pool, project):
        """Task becomes ready when all deps are done."""
        t1 = Task(
            id=gen_task_id(), project_id=project,
            title="Parent", status=TaskStatus.PENDING,
            priority=Priority.P1,
        )
        t2 = Task(
            id=gen_task_id(), project_id=project,
            title="Child", status=TaskStatus.PENDING,
            priority=Priority.P1,
            depends_on=[t1.id],
        )
        await create_tasks_batch(pool, [t1, t2])

        # Complete t1
        await claim_task(pool, t1.id, "agent-1")
        await complete_task(pool, t1.id, {"done": True})

        count = await get_ready_count(pool, project)
        assert count == 1  # t2 is now ready
