"""Claude AI context provider for Portal external integrations."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from pathlib import Path

    from portal.core.domain.models.color import WorktreeColor
    from portal.core.domain.models.worktree import Worktree


class ClaudeContextProvider:
    """Provide context for Claude AI assistant."""

    def generate_context(self, worktree: Worktree, color: WorktreeColor) -> str:
        """Generate context string for Claude."""
        context = f"""## Current Worktree Context

- **Worktree**: {worktree.name}
- **Branch**: {worktree.branch}
- **Path**: {worktree.path}
- **Color**: {color.name} ({color.hex})
- **Visual Indicator**: [{color.hex}]⬤[/{color.hex}]

This worktree is color-coded as **{color.name}** for easy identification across all tools.
When referencing this worktree, you can use the {color.name} color as a visual identifier.
"""
        return context

    def generate_project_context(self, worktrees: list[dict[str, Any]]) -> str:
        """Generate project-wide context."""
        context = "## Project Worktrees\n\n"

        for data in worktrees:
            wt = data["worktree"]
            color = data["color"]
            status = "current" if wt.is_current else ""

            context += f"- **{color.name}** {wt.name} ({wt.branch}) {status}\n"

        return context

    def create_context_file(self, worktree_path: Path, context: str) -> bool:
        """Create .claude_context file in worktree."""
        context_file = worktree_path / ".claude_context"

        try:
            with open(context_file, "w") as f:
                f.write(context)
            return True
        except Exception:
            return False

    def generate_integration_context(self, integrations_status: dict[str, Any]) -> str:
        """Generate context about available integrations."""
        context = "## Available Development Tools\n\n"

        terminals = integrations_status.get("terminals", {})
        editors = integrations_status.get("editors", {})

        if any(term["available"] for term in terminals.values()):
            context += "### Terminal Integrations\n"
            for _, status in terminals.items():
                if status["available"]:
                    context += f"- **{status['name']}**: Available ({status['version']})\n"

        if any(editor["available"] for editor in editors.values()):
            context += "\n### Editor Integrations\n"
            for _, status in editors.items():
                if status["available"]:
                    context += f"- **{status['name']}**: Available ({status['version']})\n"

        if not any(term["available"] for term in terminals.values()) and not any(
            editor["available"] for editor in editors.values()
        ):
            context += "No external integrations are currently available.\n"

        return context
