from __future__ import annotations

from collections.abc import Generator
from pathlib import Path
from unittest.mock import patch

import pygit2
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pygittools.tasks import BOARD_REF_PREFIX, TASK_REF_PREFIX, Board, Task

from pygitweb.config import settings
from pygitweb.tasks import EMPTY_TREE_OID
from pygitweb.team import team_router


def _build_client() -> TestClient:
    app = FastAPI()
    app.include_router(team_router, prefix="/team")
    return TestClient(app)


class TestTeamRoutes:
    @pytest.fixture(scope="class")
    def seeded_env(
        self, tmp_path_factory: pytest.TempPathFactory
    ) -> Generator[dict[str, str | TestClient], None, None]:
        root: Path = tmp_path_factory.mktemp("team-routes")
        repo_dir: Path = root / "demo"
        pygit2.init_repository(str(repo_dir), bare=False)
        repo = pygit2.Repository(str(repo_dir))
        project = "demo"

        board_ref = f"{BOARD_REF_PREFIX}Tasks"
        board = Board(EMPTY_TREE_OID, board_ref, tagger="", description="Main board")

        alice_task = Task(
            EMPTY_TREE_OID,
            f"{TASK_REF_PREFIX}task_alice",
            tagger="",
            title="Fix the bug",
            status=Task.Status.IN_PROGRESS,
            priority=Task.Priority.HIGH,
            assignee="alice",
            points=5,
        )
        alice_oid = alice_task.write(repo)

        done_task = Task(
            EMPTY_TREE_OID,
            f"{TASK_REF_PREFIX}task_done",
            tagger="",
            title="Already shipped",
            status=Task.Status.DONE,
            priority=Task.Priority.LOW,
            assignee="alice",
            points=13,
        )
        done_oid = done_task.write(repo)

        unassigned_task = Task(
            EMPTY_TREE_OID,
            f"{TASK_REF_PREFIX}task_open",
            tagger="",
            title="Needs an owner",
            status=Task.Status.TODO,
            priority=Task.Priority.MEDIUM,
            points=3,
        )
        unassigned_oid = unassigned_task.write(repo)

        board.tasks = [str(alice_oid), str(done_oid), str(unassigned_oid)]
        board.update_message()
        board.write(repo)

        capacity_path = root / "capacity.json"

        with (
            patch.object(settings, "PROJECTROOT", str(root)),
            patch.object(settings, "PROJECTS_LIST", str(root)),
            patch.object(settings, "STRICT_EXPORT", False),
            patch.object(settings, "EXPORT_OK", ""),
            patch.object(settings, "AUTH", False),
            patch("pygitweb.capacity_config.capacity_config_path", return_value=capacity_path),
        ):
            client = _build_client()
            yield {"client": client, "project": project}

    def test_team_page_groups_open_tasks_by_assignee(self, seeded_env: dict[str, str | TestClient]) -> None:
        client = seeded_env["client"]
        assert isinstance(client, TestClient)
        resp = client.get("/team")
        assert resp.status_code == 200
        body = resp.text
        assert "alice" in body
        assert "Fix the bug" in body
        # DONE tasks are not part of current workload.
        assert "Already shipped" not in body
        # Unassigned open tasks show up under their own bucket.
        assert "Unassigned" in body
        assert "Needs an owner" in body

    def test_capacity_form_shows_default(self, seeded_env: dict[str, str | TestClient]) -> None:
        client = seeded_env["client"]
        assert isinstance(client, TestClient)
        resp = client.get("/team/capacity", params={"user": "alice", "week": "2026-W10"})
        assert resp.status_code == 200
        assert "alice" in resp.text

    def test_capacity_submit_persists_and_reflects_on_team_page(self, seeded_env: dict[str, str | TestClient]) -> None:
        client = seeded_env["client"]
        assert isinstance(client, TestClient)
        resp = client.post(
            "/team/capacity/submit",
            data={"user": "alice", "week": "2026-W10", "points": "8"},
            follow_redirects=False,
        )
        assert resp.status_code == 303
        assert resp.headers["location"] == "/team?week=2026-W10"

        team_resp = client.get("/team", params={"week": "2026-W10"})
        assert team_resp.status_code == 200
        # alice has 5 open points against an 8-point capacity for this week.
        assert "5 / 8 pts this week" in team_resp.text

    def test_capacity_submit_rejects_invalid_week(self, seeded_env: dict[str, str | TestClient]) -> None:
        client = seeded_env["client"]
        assert isinstance(client, TestClient)
        resp = client.post(
            "/team/capacity/submit",
            data={"user": "alice", "week": "not-a-week", "points": "8"},
        )
        assert resp.status_code == 400

    def test_capacity_submit_rejects_negative_points(self, seeded_env: dict[str, str | TestClient]) -> None:
        client = seeded_env["client"]
        assert isinstance(client, TestClient)
        resp = client.post(
            "/team/capacity/submit",
            data={"user": "alice", "week": "2026-W11", "points": "-1"},
        )
        assert resp.status_code == 400