from pathlib import Path

import pytest
from pygit2 import Oid, Repository, init_repository

from pygittools.tasks import (
    BOARD_REF_PREFIX,
    TASK_REF_PREFIX,
    Board,
    Comment,
    Task,
)
from pygittools.tasks_query import (
    get_board_tasks_grouped,
    get_task_view,
    list_boards,
    list_tasks,
    resolve_task_from_board_entry,
)


@pytest.fixture
def repo(tmp_path: Path) -> Repository:
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    return init_repository(str(repo_path), bare=False)


def _empty_tree() -> Oid:
    return Oid(hex="4b825dc642cb6eb9a060e54bf8d69288fbee4904")


def test_list_boards_and_tasks_with_comments(repo: Repository) -> None:
    board_ref = f"{BOARD_REF_PREFIX}Tasks"
    board = Board(_empty_tree(), board_ref, tagger="", description="Main")
    task = Task(
        _empty_tree(),
        f"{TASK_REF_PREFIX}alpha",
        "alice <alice@example.com>",
        title="Alpha",
        description="Do alpha",
        status=Task.Status.IN_PROGRESS,
    )
    task_oid = task.write(repo)
    comment = Comment(target=task_oid, tagger="alice <alice@example.com>", content="Looks good")
    comment_oid = comment.write(repo)
    task.comments = [str(comment_oid)]
    task.update_message()
    current_task_oid = task.write(repo)
    board.tasks = [str(current_task_oid)]
    board.update_message()
    board.write(repo)

    boards = list_boards(repo)
    assert boards == [{"name": "Tasks", "description": "Main", "task_count": 1}]

    tasks = list_tasks(repo, "Tasks", include_comments=True)
    assert len(tasks) == 1
    assert tasks[0]["title"] == "Alpha"
    assert tasks[0]["status"] == "IN_PROGRESS"
    assert tasks[0]["comments"] == [
        {
            "content": "Looks good",
            "author": "alice <alice@example.com>",
            "created_at": tasks[0]["comments"][0]["created_at"],
            "edited_at": tasks[0]["comments"][0]["edited_at"],
        }
    ]

    detail = get_task_view(repo, "alpha")
    assert detail["comments"][0]["content"] == "Looks good"

    columns = get_board_tasks_grouped(repo, "Tasks")
    assert columns[1]["status"] == "IN_PROGRESS"
    assert columns[1]["tasks"][0]["title"] == "Alpha"


def test_resolve_task_from_board_entry_follows_current_ref(repo: Repository) -> None:
    task = Task(
        _empty_tree(),
        f"{TASK_REF_PREFIX}stale",
        "alice <alice@example.com>",
        title="Stale board entry",
        status=Task.Status.TODO,
    )
    stale_oid = task.write(repo)
    task.title = "Current title"
    task.status = Task.Status.DONE
    task.update_message()
    current_oid = task.write(repo)

    loaded = resolve_task_from_board_entry(repo, stale_oid)
    assert loaded is not None
    assert loaded.title == "Current title"
    assert loaded.status == Task.Status.DONE
    assert str(current_oid) != str(stale_oid)