# this_file: claif_cla/src/claif_cla/install.py

import shutil
from pathlib import Path

from loguru import logger

# Import common install functionality
try:
    from claif.common.utils import prompt_tool_configuration
    from claif.install import (
        bundle_all_tools,
        ensure_bun_installed,
        get_install_location,
        install_npm_package_globally,
        uninstall_tool,
    )
except ImportError:
    # Fallback if claif package not available
    logger.warning("claif package not found, using local implementations")
    from claif_cla.install_fallback import (
        bundle_all_tools,
        ensure_bun_installed,
        get_install_location,
        install_npm_package_globally,
        uninstall_tool,
    )

    def prompt_tool_configuration(tool_name: str, config_commands: list[str]) -> None:
        """Fallback implementation for tool configuration prompt."""
        if config_commands:
            for _cmd in config_commands:
                pass


def install_claude_bundled(install_dir: Path, dist_dir: Path) -> bool:
    """Install bundled Claude (requires directory structure)."""
    try:
        claude_source = dist_dir / "claude"
        if not claude_source.exists():
            logger.error("Bundled Claude not found")
            return False

        # Create installation directory for Claude (with -bin suffix to avoid conflict)
        claude_install_dir = install_dir / "claude-bin"
        if claude_install_dir.exists():
            shutil.rmtree(claude_install_dir)

        # Copy the entire Claude directory (executable + yoga.wasm)
        shutil.copytree(claude_source, claude_install_dir)

        # Create wrapper script that runs Claude from its directory
        wrapper_path = install_dir / "claude"
        if wrapper_path.exists():
            wrapper_path.unlink()  # Remove existing file/symlink

        wrapper_content = f"""#!/usr/bin/env bash
# Claude CLI wrapper script
# Generated by claif install

# Change to Claude directory and run the executable
cd "{claude_install_dir}" && exec ./claude "$@"
"""

        wrapper_path.write_text(wrapper_content)
        wrapper_path.chmod(0o755)

        logger.success(f"✓ Claude installed at {claude_install_dir}")
        return True

    except Exception as e:
        logger.error(f"Failed to install Claude: {e}")
        return False


def install_claude() -> dict:
    """Install Claude CLI with bundled approach."""
    if not ensure_bun_installed():
        return {"installed": [], "failed": ["claude"], "message": "bun installation failed"}

    install_dir = get_install_location()

    # Install npm package globally first
    logger.info("Installing @anthropic-ai/claude-code...")
    if not install_npm_package_globally("@anthropic-ai/claude-code"):
        return {"installed": [], "failed": ["claude"], "message": "@anthropic-ai/claude-code installation failed"}

    # Bundle all tools (this creates the dist directory with all tools)
    logger.info("Bundling CLI tools...")
    dist_dir = bundle_all_tools()
    if not dist_dir:
        return {"installed": [], "failed": ["claude"], "message": "bundling failed"}

    # Install Claude specifically
    logger.info("Installing claude...")
    if install_claude_bundled(install_dir, dist_dir):
        logger.success("🎉 Claude installed successfully!")
        logger.info("You can now use 'claude' command from anywhere")

        # Prompt for configuration
        config_commands = [
            "claude auth login",
            "claude --help",
        ]
        prompt_tool_configuration("Claude", config_commands)

        return {"installed": ["claude"], "failed": []}
    return {"installed": [], "failed": ["claude"], "message": "claude installation failed"}


def uninstall_claude() -> dict:
    """Uninstall Claude CLI."""
    logger.info("Uninstalling claude...")

    if uninstall_tool("claude"):
        logger.success("✓ Claude uninstalled successfully")
        return {"uninstalled": ["claude"], "failed": []}
    return {"uninstalled": [], "failed": ["claude"], "message": "claude uninstallation failed"}


def is_claude_installed() -> bool:
    """Check if Claude is installed."""
    install_dir = get_install_location()
    claude_executable = install_dir / "claude"
    claude_dir = install_dir / "claude"

    return (claude_executable.exists() and claude_executable.is_file()) or (claude_dir.exists() and claude_dir.is_dir())


def get_claude_status() -> dict:
    """Get Claude installation status."""
    if is_claude_installed():
        install_dir = get_install_location()
        claude_path = install_dir / "claude"
        return {"installed": True, "path": str(claude_path), "type": "bundled (claif-owned)"}
    return {"installed": False, "path": None, "type": None}
