"""Integration tests for the yagra init command."""

import subprocess
from pathlib import Path

import pytest


@pytest.fixture
def test_dir(tmp_path: Path) -> Path:
    """Creates a directory for testing.

    Args:
        tmp_path: A pytest temporary directory.

    Returns:
        The path to the test directory.
    """
    test_dir = tmp_path / "test-workflow"
    test_dir.mkdir()
    return test_dir


def test_yagra_init_list_command() -> None:
    """Confirms that the yagra init --list command works correctly."""
    result = subprocess.run(
        ["uv", "run", "yagra", "init", "--list"],
        capture_output=True,
        text=True,
        check=False,
    )

    assert result.returncode == 0
    assert "branch" in result.stdout
    assert "loop" in result.stdout
    assert "rag" in result.stdout
    assert "parallel" in result.stdout
    assert "subgraph" in result.stdout
    assert "chat" in result.stdout


def test_yagra_init_creates_workflow(test_dir: Path) -> None:
    """Confirms that a workflow is generated by the yagra init --template command."""
    result = subprocess.run(
        ["uv", "run", "yagra", "init", "--template", "branch", "--output", str(test_dir)],
        capture_output=True,
        text=True,
        check=False,
    )

    assert result.returncode == 0
    assert "Initialized from template" in result.stdout
    assert "workflow is valid." in result.stdout

    # Verify that the files have been generated
    assert (test_dir / "workflow.yaml").exists()
    assert (test_dir / "prompts" / "branch_prompts.yaml").exists()


def test_yagra_init_validates_generated_workflow(test_dir: Path) -> None:
    """Confirms that a generated workflow passes validation."""
    # Generate from template
    subprocess.run(
        ["uv", "run", "yagra", "init", "--template", "loop", "--output", str(test_dir)],
        capture_output=True,
        check=True,
    )

    # Validate using the validate command
    result = subprocess.run(
        ["uv", "run", "yagra", "validate", "--workflow", str(test_dir / "workflow.yaml")],
        capture_output=True,
        text=True,
        check=False,
    )

    assert result.returncode == 0


def test_yagra_init_fails_without_template() -> None:
    """Confirms that running without specifying --template results in an error."""
    result = subprocess.run(
        ["uv", "run", "yagra", "init"],
        capture_output=True,
        text=True,
        check=False,
    )

    assert result.returncode == 2
    assert "Error:" in result.stderr or "specify either" in result.stderr


def test_yagra_init_fails_with_invalid_template(test_dir: Path) -> None:
    """Confirms that specifying a nonexistent template results in an error."""
    result = subprocess.run(
        ["uv", "run", "yagra", "init", "--template", "invalid", "--output", str(test_dir)],
        capture_output=True,
        text=True,
        check=False,
    )

    assert result.returncode == 1
    assert "not found" in result.stderr


def test_yagra_init_prevents_overwrite_without_force(test_dir: Path) -> None:
    """Confirms that existing files are not overwritten without --force."""
    # First initialization
    subprocess.run(
        ["uv", "run", "yagra", "init", "--template", "branch", "--output", str(test_dir)],
        capture_output=True,
        check=True,
    )

    # Second initialization (without --force)
    result = subprocess.run(
        ["uv", "run", "yagra", "init", "--template", "branch", "--output", str(test_dir)],
        capture_output=True,
        text=True,
        check=False,
    )

    assert result.returncode == 1
    assert "Files already exist" in result.stderr
    assert "--force" in result.stderr


@pytest.mark.parametrize("template", ["parallel", "subgraph", "chat"])
def test_yagra_init_creates_new_template(test_dir: Path, template: str) -> None:
    """Confirms that new templates (parallel, subgraph, chat) can be initialized and validated."""
    result = subprocess.run(
        ["uv", "run", "yagra", "init", "--template", template, "--output", str(test_dir)],
        capture_output=True,
        text=True,
        check=False,
    )

    assert result.returncode == 0, f"init failed for template '{template}': {result.stderr}"
    assert "Initialized from template" in result.stdout
    assert "workflow is valid." in result.stdout
    assert (test_dir / "workflow.yaml").exists()


def test_yagra_init_overwrites_with_force(test_dir: Path) -> None:
    """Confirms that existing files are overwritten when the --force flag is used."""
    # First initialization
    subprocess.run(
        ["uv", "run", "yagra", "init", "--template", "branch", "--output", str(test_dir)],
        capture_output=True,
        check=True,
    )

    workflow_file = test_dir / "workflow.yaml"

    # Manually modify the file
    workflow_file.write_text("modified content")

    # Second initialization (with --force)
    result = subprocess.run(
        [
            "uv",
            "run",
            "yagra",
            "init",
            "--template",
            "branch",
            "--output",
            str(test_dir),
            "--force",
        ],
        capture_output=True,
        text=True,
        check=False,
    )

    assert result.returncode == 0

    # Verify that the file has been restored to the original template content
    new_content = workflow_file.read_text()
    assert "modified content" not in new_content
    assert "version:" in new_content
