"""Shared test fixtures for Hangar backend."""

from pathlib import Path

import pytest
from fastapi.testclient import TestClient

from hangar.dependencies import set_project_path
from hangar.main import app

from tests.helpers import SAMPLE_CONFIG_YAML, SAMPLE_TASKS_MD


# ── Unit test fixtures ─────────────────────────────────────────────


@pytest.fixture
def client() -> TestClient:
    """Create a FastAPI test client."""
    return TestClient(app)


# ── Integration fixtures ──────────────────────────────────────────


@pytest.fixture
def integration_project(tmp_path: Path) -> Path:
    """Create a full project layout for integration tests.

    Creates:
        tmp_path/
            .beads/
            openspec/
                config.yaml
                changes/
                    test-feature/
                        tasks.md
                        .description
                        proposal.md

    Calls set_project_path(tmp_path) so all DI singletons point here.
    """
    # .beads directory (marker for project root)
    (tmp_path / ".beads").mkdir()

    # openspec structure
    changes_dir = tmp_path / "openspec" / "changes" / "test-feature"
    changes_dir.mkdir(parents=True)

    # config.yaml
    config_path = tmp_path / "openspec" / "config.yaml"
    config_path.write_text(SAMPLE_CONFIG_YAML)

    # tasks.md
    tasks_md = changes_dir / "tasks.md"
    tasks_md.write_text(SAMPLE_TASKS_MD)

    # .description (for wizard state recovery)
    desc_file = changes_dir / ".description"
    desc_file.write_text("Test feature for integration testing")

    # proposal.md (for wizard state — shows step 0 approved)
    proposal = changes_dir / "proposal.md"
    proposal.write_text("# Proposal\n\nThis is a test proposal.\n")

    # Reset DI singletons to point at this project
    set_project_path(tmp_path)

    yield tmp_path

    # Cleanup: reset DI state so other tests aren't affected
    app.dependency_overrides.clear()


@pytest.fixture
def integration_client(integration_project: Path) -> TestClient:
    """TestClient wired to real DI singletons (NO dependency_overrides).

    Uses the integration_project fixture to ensure project_path is set
    and the filesystem has the expected layout.

    Tests using this fixture should mock at the subprocess level
    (asyncio.create_subprocess_exec), not at the service level.
    """
    # Ensure no overrides — we want the REAL DI chain
    app.dependency_overrides.clear()
    return TestClient(app)
