"""Shared test fixtures."""

from __future__ import annotations

import json
from pathlib import Path

import pytest


@pytest.fixture
def tmp_project(tmp_path: Path) -> Path:
    """Create a minimal uv project structure in a temp directory."""
    # pyproject.toml
    (tmp_path / "pyproject.toml").write_text(
        '[project]\nname = "test-project"\nversion = "0.1.0"\n'
    )
    # src layout
    lib_dir = tmp_path / "src" / "test_project"
    lib_dir.mkdir(parents=True)
    (lib_dir / "__init__.py").write_text("")
    return tmp_path


@pytest.fixture
def abreka_project(tmp_project: Path) -> Path:
    """Create a tmp project with abreka already initialized."""
    abreka_dir = tmp_project / "abreka"
    abreka_dir.mkdir()
    (abreka_dir / "experiments").mkdir()
    (abreka_dir / "prompts").mkdir()
    (abreka_dir / "artifacts" / "shared").mkdir(parents=True)

    # config.toml
    import tomli_w
    config = {
        "project": {"name": "test-project", "lib": "test_project", "test_command": "uv run pytest"},
        "experiment": {"primary_metric": "val:accuracy", "metric_direction": "maximize", "run_template": "./run.py"},
        "run": {"timeout_minutes": 30, "require_tests": True},
        "agent": {"provider": "openai-codex", "model": "gpt-5.4", "thinking_level": "xhigh"},
    }
    with open(abreka_dir / "config.toml", "wb") as f:
        tomli_w.dump(config, f)

    # goal.md
    (abreka_dir / "goal.md").write_text("# Test Goal\nAchieve high accuracy.\n")

    # index.json
    (abreka_dir / "index.json").write_text("{}\n")

    # backlog
    (abreka_dir / "backlog").mkdir()
    (abreka_dir / "backlog_index.json").write_text("{}\n")

    # Default prompts
    for name in ("propose_exploit", "propose_explore", "implement", "test", "repair_run", "evaluate"):
        template = f"# {name}\n{{{{goal}}}}\n"
        if name.startswith("propose"):
            template += "{{guidance}}\n"
        (abreka_dir / "prompts" / f"{name}.md").write_text(template)

    return tmp_project
