"""Tests for ievo.core.config."""

from __future__ import annotations

from pathlib import Path

import pytest

from ievo.core.config import CLAUDE_AGENTS_DIR, ensure_project_dir, find_project_root


def test_find_project_root_found(tmp_path: Path) -> None:
    (tmp_path / ".ievo").mkdir()
    (tmp_path / ".ievo/manifest.yaml").write_text("project: test\n")
    sub = tmp_path / "src" / "deep"
    sub.mkdir(parents=True)
    assert find_project_root(sub) == tmp_path


def test_find_project_root_at_root(tmp_path: Path) -> None:
    (tmp_path / ".ievo").mkdir()
    (tmp_path / ".ievo/manifest.yaml").write_text("project: test\n")
    assert find_project_root(tmp_path) == tmp_path


def test_find_project_root_not_found(tmp_path: Path) -> None:
    sub = tmp_path / "no_project" / "here"
    sub.mkdir(parents=True)
    assert find_project_root(sub) is None


def test_require_project_exits_when_not_found(tmp_path: Path) -> None:
    import typer

    from ievo.core.config import require_project

    with pytest.raises(typer.Exit):
        require_project(tmp_path)


def test_require_project_returns_root(tmp_project: Path) -> None:
    from ievo.core.config import require_project

    assert require_project(tmp_project) == tmp_project


def test_ensure_project_dir(tmp_path: Path) -> None:
    result = ensure_project_dir(tmp_path)
    assert result == tmp_path / ".ievo"
    assert result.is_dir()


def test_ensure_project_dir_idempotent(tmp_path: Path) -> None:
    ensure_project_dir(tmp_path)
    ensure_project_dir(tmp_path)  # should not raise
    assert (tmp_path / ".ievo").is_dir()


def test_claude_agents_dir_constant() -> None:
    """CLAUDE_AGENTS_DIR points to .claude/agents."""
    assert CLAUDE_AGENTS_DIR == ".claude/agents"


def test_ensure_home_creates_dirs_and_keys(tmp_path: Path) -> None:
    from unittest.mock import patch

    from ievo.core.config import ensure_home

    fake_home = tmp_path / ".ievo"
    fake_cache = fake_home / "cache"

    with (
        patch("ievo.core.config.IEVO_HOME", fake_home),
        patch("ievo.core.config.CACHE_DIR", fake_cache),
    ):
        result = ensure_home()

    assert result == fake_home
    assert fake_home.exists()
    assert fake_cache.exists()
    # Keys should be generated on first creation
    assert (fake_home / "ievo_key").exists()
    assert (fake_home / "ievo_key.pub").exists()


def test_ensure_home_idempotent(tmp_path: Path) -> None:
    from unittest.mock import patch

    from ievo.core.config import ensure_home

    fake_home = tmp_path / ".ievo"
    fake_cache = fake_home / "cache"

    with (
        patch("ievo.core.config.IEVO_HOME", fake_home),
        patch("ievo.core.config.CACHE_DIR", fake_cache),
    ):
        ensure_home()
        key_content = (fake_home / "ievo_key").read_bytes()
        ensure_home()  # second call should not regenerate keys
        assert (fake_home / "ievo_key").read_bytes() == key_content
