"""Tests for the project management router."""

from pathlib import Path
from unittest.mock import patch

import pytest
from fastapi.testclient import TestClient

from hangar.main import app

client = TestClient(app)


def test_get_current_project() -> None:
    """GET /api/project/current should return current project info."""
    with patch("hangar.routers.project.get_project_path") as mock_path:
        mock_path.return_value = Path("/home/user/my-project")
        resp = client.get("/api/project/current")

    assert resp.status_code == 200
    data = resp.json()
    assert data["name"] == "my-project"
    assert data["path"] == "/home/user/my-project"


def test_open_project_success(tmp_path: Path) -> None:
    """POST /api/project/open should switch to a valid project."""
    # Create a valid project directory
    (tmp_path / ".beads").mkdir()
    target = str(tmp_path)

    with patch("hangar.routers.project.set_project_path") as mock_set:
        resp = client.post("/api/project/open", json={"path": target})

    assert resp.status_code == 200
    data = resp.json()
    assert data["status"] == "ok"
    assert data["project"]["name"] == tmp_path.name
    assert data["project"]["path"] == str(tmp_path.resolve())
    mock_set.assert_called_once_with(tmp_path.resolve())


def test_open_project_with_openspec(tmp_path: Path) -> None:
    """POST /api/project/open should accept projects with openspec/ dir."""
    (tmp_path / "openspec").mkdir()
    target = str(tmp_path)

    with patch("hangar.routers.project.set_project_path"):
        resp = client.post("/api/project/open", json={"path": target})

    assert resp.status_code == 200
    assert resp.json()["status"] == "ok"


def test_open_project_not_found() -> None:
    """POST /api/project/open should return 404 for missing directory."""
    resp = client.post("/api/project/open", json={"path": "/nonexistent/path"})
    assert resp.status_code == 404
    assert "not found" in resp.json()["detail"].lower()


def test_open_project_not_hangar_project(tmp_path: Path) -> None:
    """POST /api/project/open should return 400 for directories without project markers."""
    target = str(tmp_path)
    resp = client.post("/api/project/open", json={"path": target})
    assert resp.status_code == 400
    assert "Not a Hangar project" in resp.json()["detail"]
