"""Tests for CLI functionality."""

import subprocess
import tempfile
from pathlib import Path

from click.testing import CliRunner

from ai_forge import cli, dev


def test_build_command_default() -> None:
    """Test default build command."""
    runner = CliRunner()

    with tempfile.TemporaryDirectory() as tmp_dir:
        output_path = Path(tmp_dir) / "test_output.md"

        result = runner.invoke(dev, ["build", "--output", str(output_path)])

        assert result.exit_code == 0
        assert "Successfully built" in result.output
        assert output_path.exists()


def test_build_command_all_targets() -> None:
    """Test build command with --all-targets flag."""
    runner = CliRunner()

    with tempfile.TemporaryDirectory() as tmp_dir:
        output_dir = Path(tmp_dir)
        output_path = output_dir / "CLAUDE.md"

        result = runner.invoke(
            dev, ["build", "--all-targets", "--output", str(output_path)]
        )

        assert result.exit_code == 0
        assert "Successfully built all targets" in result.output

        # Check all expected files exist
        expected_files = [
            output_dir / "CLAUDE.md",
            output_dir / ".claude" / "settings.json",
        ]

        for file_path in expected_files:
            assert file_path.exists(), f"Expected file {file_path} was not created"


def test_init_command() -> None:
    """Test init command."""
    runner = CliRunner()

    with tempfile.TemporaryDirectory() as tmp_dir:
        output_dir = Path(tmp_dir)

        result = runner.invoke(cli, ["init", str(output_dir)])

        assert result.exit_code == 0
        assert "Successfully initialized" in result.output
        assert "Generated files:" in result.output

        # Check all expected files exist
        expected_files = [
            output_dir / "CLAUDE.md",
            output_dir / ".claude" / "settings.json",
        ]

        for file_path in expected_files:
            assert file_path.exists(), f"Expected file {file_path} was not created"


def test_build_with_custom_directories() -> None:
    """Test build command with custom snippets and templates directories."""
    runner = CliRunner()

    with tempfile.TemporaryDirectory() as tmp_dir:
        output_path = Path(tmp_dir) / "custom_output.md"

        result = runner.invoke(
            dev,
            [
                "build",
                "--snippets-dir",
                "snippets",
                "--templates-dir",
                "templates",
                "--output",
                str(output_path),
            ],
        )

        assert result.exit_code == 0
        assert "Successfully built" in result.output
        assert output_path.exists()


def test_init_with_default_behavior() -> None:
    """Test init command with default behavior (bundled resources)."""
    runner = CliRunner()

    with tempfile.TemporaryDirectory() as tmp_dir:
        output_dir = Path(tmp_dir)

        result = runner.invoke(cli, ["init", str(output_dir)])

        assert result.exit_code == 0
        assert "Successfully initialized" in result.output

        # Check that bundled resources created all expected files
        expected_files = [
            output_dir / "CLAUDE.md",
            output_dir / ".claude" / "settings.json",
            output_dir / "PROJECT_CHARTER.md",
            output_dir / "TASK_BOARD.md",
            output_dir / "artifacts" / "README.md",
            output_dir / "contracts" / "README.md",
        ]

        for file_path in expected_files:
            assert file_path.exists(), f"Expected file {file_path} was not created"


def test_main_entry_point() -> None:
    """Test main entry point function."""
    # This test just ensures the main function can be called without errors
    # We can't easily test the CLI interaction, but we can test that it doesn't crash
    runner = CliRunner()
    result = runner.invoke(cli, ["--help"])
    assert result.exit_code == 0
    assert "AI Forge - Claude Collective Builder" in result.output


def test_cli_integration_with_real_commands() -> None:
    """Test CLI integration using subprocess (closer to real usage)."""
    # Test basic build command
    result = subprocess.run(
        ["uv", "run", "python", "-m", "ai_forge", "dev", "build", "--help"],
        capture_output=True,
        text=True,
    )

    assert result.returncode == 0
    assert "Build CLAUDE.md from snippets" in result.stdout

    # Test init command
    result = subprocess.run(
        ["uv", "run", "python", "-m", "ai_forge", "init", "--help"],
        capture_output=True,
        text=True,
    )

    assert result.returncode == 0
    assert "Initialize a Claude Collective project" in result.stdout


def test_cli_error_handling() -> None:
    """Test CLI error handling for invalid paths."""
    runner = CliRunner()

    result = runner.invoke(
        dev,
        ["build", "--snippets-dir", "nonexistent", "--output", "/tmp/test.md"],
    )

    # The command may succeed but with errors in output, or it may fail
    # Let's check that either it fails or shows an error message
    assert (
        result.exit_code != 0
        or "Build failed" in result.output
        or "not found" in result.output
    )


def test_init_bundled_resources() -> None:
    """Test that init command works with bundled resources anywhere on filesystem."""
    runner = CliRunner()

    with tempfile.TemporaryDirectory() as tmp_dir:
        output_dir = Path(tmp_dir) / "test_project"
        output_dir.mkdir()

        # This should work without requiring external snippets/templates
        result = runner.invoke(cli, ["init", str(output_dir)])

        assert result.exit_code == 0
        assert "Successfully initialized" in result.output
        assert output_dir.exists()

        # Verify critical files exist
        assert (output_dir / "CLAUDE.md").exists()
        assert (output_dir / ".claude" / "settings.json").exists()
