"""Tests for the /api/sync router endpoints."""

import pytest
from unittest.mock import AsyncMock, patch
from pathlib import Path

from fastapi.testclient import TestClient

from hangar.main import app
from hangar.dependencies import set_project_path
from hangar.services.importsync import (
    ImportPreview,
    ImportResult,
    SyncResult,
    ChangeCompletion,
    ParsedTask,
    SuggestedDep,
)


SAMPLE_TASKS_MD = """\
# Tasks: Test

## Phase 1: Setup

- [ ] **1.1** Create models
  - Tests: models parse correctly
- [ ] **1.2** Create service
  - Tests: service works
"""


@pytest.fixture
def tmp_project(tmp_path):
    changes_dir = tmp_path / "openspec" / "changes" / "test-feature"
    changes_dir.mkdir(parents=True)
    (changes_dir / "tasks.md").write_text(SAMPLE_TASKS_MD)
    # Also create .beads dir so project discovery works
    (tmp_path / ".beads").mkdir()
    set_project_path(tmp_path)
    return tmp_path


@pytest.fixture
def client(tmp_project):
    return TestClient(app)


class TestPreviewEndpoint:
    def test_preview_returns_tasks(self, client):
        res = client.get("/api/sync/test-feature/preview")
        assert res.status_code == 200
        data = res.json()
        assert data["change_name"] == "test-feature"
        assert len(data["tasks"]) == 2
        assert len(data["to_import"]) == 2
        assert len(data["already_imported"]) == 0

    def test_preview_includes_deps(self, client):
        res = client.get("/api/sync/test-feature/preview")
        data = res.json()
        assert len(data["suggested_deps"]) == 1
        assert data["suggested_deps"][0]["from_number"] == "1.1"
        assert data["suggested_deps"][0]["to_number"] == "1.2"

    def test_preview_missing_change(self, client):
        res = client.get("/api/sync/nonexistent/preview")
        assert res.status_code == 404


class TestCompletionEndpoint:
    def test_completion_no_imports(self, client):
        res = client.get("/api/sync/test-feature/completion")
        assert res.status_code == 200
        data = res.json()
        assert data["total"] == 2
        assert data["open"] == 2
        assert data["closed"] == 0

    def test_completion_missing_change(self, client):
        res = client.get("/api/sync/nonexistent/completion")
        assert res.status_code == 404
