"""Tests for abreka init command."""

import json
from pathlib import Path

from click.testing import CliRunner

from abreka.cli import main


class TestInitCommand:
    def test_init_creates_structure(self, tmp_project):
        runner = CliRunner()
        with runner.isolated_filesystem(temp_dir=tmp_project) as td:
            # Copy project files into isolated dir
            pass

        result = runner.invoke(main, ["init", str(tmp_project)])
        assert result.exit_code == 0, result.output

        abreka_dir = tmp_project / "abreka"
        assert (abreka_dir / "config.toml").is_file()
        assert (abreka_dir / "goal.md").is_file()
        assert (abreka_dir / "index.json").is_file()
        assert (abreka_dir / "experiments").is_dir()
        assert (abreka_dir / "artifacts" / "shared").is_dir()
        assert (abreka_dir / "prompts" / "propose_exploit.md").is_file()
        assert (abreka_dir / "prompts" / "propose_explore.md").is_file()
        assert (abreka_dir / "prompts" / "implement.md").is_file()
        assert (abreka_dir / "prompts" / "test.md").is_file()
        assert (abreka_dir / "prompts" / "repair_run.md").is_file()
        assert (abreka_dir / "prompts" / "evaluate.md").is_file()
        assert (abreka_dir / "wiki" / "pages").is_dir()
        assert (abreka_dir / "wiki_index.json").is_file()

        # Verify index is empty JSON
        index = json.loads((abreka_dir / "index.json").read_text())
        assert index == {}
        wiki_index = json.loads((abreka_dir / "wiki_index.json").read_text())
        assert wiki_index == {}

        # Verify .rgignore excludes experiment artifacts but keeps shared artifacts searchable
        rgignore = abreka_dir / ".rgignore"
        assert rgignore.is_file()
        content = rgignore.read_text()
        assert "experiments/*/artifacts/" in content
        assert "artifacts/*" in content
        assert "!artifacts/shared/" in content
        assert "!artifacts/shared/**" in content

    def test_init_detects_project(self, tmp_project):
        runner = CliRunner()
        result = runner.invoke(main, ["init", str(tmp_project)])
        assert "test-project" in result.output
        assert "test_project" in result.output

    def test_init_refuses_reinit(self, abreka_project):
        runner = CliRunner()
        result = runner.invoke(main, ["init", str(abreka_project)])
        assert result.exit_code != 0
        assert "already initialized" in result.output
