"""ErkImplWorkflowCapability - GitHub Action for automated implementation."""

import shutil
from pathlib import Path

from erk.core.capabilities.base import (
    Capability,
    CapabilityArtifact,
    CapabilityResult,
    CapabilityScope,
    ManagedArtifact,
)


class ErkImplWorkflowCapability(Capability):
    """GitHub Action for automated implementation workflow.

    Installs:
    - .github/workflows/plan-implement.yml
    - .github/actions/setup-claude-code/
    - .github/actions/setup-claude-erk/
    """

    @property
    def name(self) -> str:
        return "erk-impl-workflow"

    @property
    def description(self) -> str:
        return "GitHub Action for automated implementation"

    @property
    def scope(self) -> CapabilityScope:
        return "project"

    @property
    def installation_check_description(self) -> str:
        return ".github/workflows/plan-implement.yml exists"

    @property
    def artifacts(self) -> list[CapabilityArtifact]:
        return [
            CapabilityArtifact(
                path=".github/workflows/plan-implement.yml",
                artifact_type="file",
            ),
            CapabilityArtifact(
                path=".github/actions/setup-claude-code/",
                artifact_type="directory",
            ),
            CapabilityArtifact(
                path=".github/actions/setup-claude-erk/",
                artifact_type="directory",
            ),
        ]

    @property
    def managed_artifacts(self) -> list[ManagedArtifact]:
        """Declare workflow and actions as managed artifacts."""
        return [
            ManagedArtifact(name="plan-implement", artifact_type="workflow"),
            ManagedArtifact(name="setup-claude-code", artifact_type="action"),
            ManagedArtifact(name="setup-claude-erk", artifact_type="action"),
        ]

    def is_installed(self, repo_root: Path | None) -> bool:
        """Check if the workflow file exists."""
        assert repo_root is not None, "ErkImplWorkflowCapability requires repo_root"
        return (repo_root / ".github" / "workflows" / "plan-implement.yml").exists()

    def install(self, repo_root: Path | None) -> CapabilityResult:
        """Install the workflow and related actions."""
        assert repo_root is not None, "ErkImplWorkflowCapability requires repo_root"
        # Inline import: avoids circular dependency with artifacts module
        from erk.artifacts.state import add_installed_capability
        from erk.artifacts.sync import get_bundled_github_dir

        bundled_github_dir = get_bundled_github_dir()
        if not bundled_github_dir.exists():
            return CapabilityResult(
                success=False,
                message="Bundled .github/ not found in erk package",
            )

        installed_count = 0

        # Install workflow
        workflow_src = bundled_github_dir / "workflows" / "plan-implement.yml"
        if workflow_src.exists():
            workflow_dst = repo_root / ".github" / "workflows" / "plan-implement.yml"
            workflow_dst.parent.mkdir(parents=True, exist_ok=True)
            shutil.copy2(workflow_src, workflow_dst)
            installed_count += 1

        # Install actions
        actions = ["setup-claude-code", "setup-claude-erk"]
        for action_name in actions:
            action_src = bundled_github_dir / "actions" / action_name
            if action_src.exists():
                action_dst = repo_root / ".github" / "actions" / action_name
                action_dst.mkdir(parents=True, exist_ok=True)
                self._copy_directory(action_src, action_dst)
                installed_count += 1

        if installed_count == 0:
            return CapabilityResult(
                success=False,
                message="No workflow artifacts found in erk package",
            )

        # Record capability installation
        add_installed_capability(repo_root, self.name)

        return CapabilityResult(
            success=True,
            message=f"Installed plan-implement workflow ({installed_count} artifacts)",
        )

    def uninstall(self, repo_root: Path | None) -> CapabilityResult:
        """Remove the plan-implement workflow and related actions."""
        assert repo_root is not None, "ErkImplWorkflowCapability requires repo_root"
        from erk.artifacts.state import remove_installed_capability

        removed: list[str] = []

        # Remove workflow
        workflow_file = repo_root / ".github" / "workflows" / "plan-implement.yml"
        if workflow_file.exists():
            workflow_file.unlink()
            removed.append(".github/workflows/plan-implement.yml")

        # Remove actions
        actions = ["setup-claude-code", "setup-claude-erk"]
        for action_name in actions:
            action_dir = repo_root / ".github" / "actions" / action_name
            if action_dir.exists():
                shutil.rmtree(action_dir)
                removed.append(f".github/actions/{action_name}/")

        # Remove from installed capabilities
        remove_installed_capability(repo_root, self.name)

        if not removed:
            return CapabilityResult(
                success=True,
                message="erk-impl-workflow not installed",
            )

        return CapabilityResult(
            success=True,
            message=f"Removed {', '.join(removed)}",
        )

    def _copy_directory(self, source: Path, target: Path) -> None:
        """Copy directory contents recursively."""
        for source_path in source.rglob("*"):
            if source_path.is_file():
                relative = source_path.relative_to(source)
                target_path = target / relative
                target_path.parent.mkdir(parents=True, exist_ok=True)
                shutil.copy2(source_path, target_path)
