"""
Shell tab completion for the sovereign agent CLI.

Generates and installs completion scripts for bash, zsh, and fish.
Uses Click's built-in completion mechanism via the
_SKCAPSTONE_COMPLETE environment variable.

Supported shells:
    - bash: sources from ~/.bashrc or ~/.bash_completion.d/
    - zsh:  sources from ~/.zshrc or ~/.zfunc/
    - fish: sources from ~/.config/fish/completions/

Usage:
    skcapstone completions install         # auto-detect shell, install
    skcapstone completions install --shell bash
    skcapstone completions show --shell zsh # print script to stdout
    skcapstone completions uninstall       # remove installed scripts
"""

from __future__ import annotations

import os
import subprocess
from pathlib import Path
from typing import Optional


SUPPORTED_SHELLS = ("bash", "zsh", "fish")

COMPLETION_SCRIPTS = {
    "bash": """\
# skcapstone bash completion — generated by skcapstone completions install
eval "$(_SKCAPSTONE_COMPLETE=bash_source skcapstone)"
""",
    "zsh": """\
# skcapstone zsh completion — generated by skcapstone completions install
eval "$(_SKCAPSTONE_COMPLETE=zsh_source skcapstone)"
""",
    "fish": """\
# skcapstone fish completion — generated by skcapstone completions install
_SKCAPSTONE_COMPLETE=fish_source skcapstone | source
""",
}

INSTALL_PATHS = {
    "bash": Path.home() / ".bash_completion.d" / "skcapstone.bash-completion",
    "zsh": Path.home() / ".zfunc" / "_skcapstone",
    "fish": Path.home() / ".config" / "fish" / "completions" / "skcapstone.fish",
}

RC_MARKERS = {
    "bash": (
        Path.home() / ".bashrc",
        '[ -f ~/.bash_completion.d/skcapstone.bash-completion ] && source ~/.bash_completion.d/skcapstone.bash-completion',
    ),
    "zsh": (
        Path.home() / ".zshrc",
        '[ -f ~/.zfunc/_skcapstone ] && source ~/.zfunc/_skcapstone',
    ),
}


def detect_shell() -> Optional[str]:
    """Detect the current shell from environment.

    Returns:
        str: Shell name (bash, zsh, fish) or None.
    """
    shell_path = os.environ.get("SHELL", "")
    for s in SUPPORTED_SHELLS:
        if s in shell_path:
            return s
    return None


def generate_script(shell: str) -> str:
    """Generate the completion script for a shell.

    Args:
        shell: Shell name (bash, zsh, fish).

    Returns:
        str: Completion script content.

    Raises:
        ValueError: If the shell is not supported.
    """
    if shell not in SUPPORTED_SHELLS:
        raise ValueError(
            f"Unsupported shell: {shell}. "
            f"Supported: {', '.join(SUPPORTED_SHELLS)}"
        )
    return COMPLETION_SCRIPTS[shell]


def install_completions(shell: Optional[str] = None) -> dict:
    """Install tab completion for the specified shell.

    Writes the completion script to the appropriate location and
    optionally adds a source line to the shell RC file.

    Args:
        shell: Shell name. Auto-detected if None.

    Returns:
        dict: Installation result with 'shell', 'script_path', 'rc_updated'.
    """
    shell = shell or detect_shell()
    if not shell:
        return {
            "success": False,
            "error": "Could not detect shell. Use --shell bash/zsh/fish.",
        }

    script = generate_script(shell)
    script_path = INSTALL_PATHS[shell]

    script_path.parent.mkdir(parents=True, exist_ok=True)
    script_path.write_text(script, encoding="utf-8")

    result = {
        "success": True,
        "shell": shell,
        "script_path": str(script_path),
        "rc_updated": False,
    }

    if shell in RC_MARKERS:
        rc_path, source_line = RC_MARKERS[shell]
        if rc_path.exists():
            rc_content = rc_path.read_text(encoding="utf-8")
            if source_line not in rc_content:
                with open(rc_path, "a", encoding="utf-8") as f:
                    f.write(f"\n# skcapstone tab completion\n{source_line}\n")
                result["rc_updated"] = True
                result["rc_path"] = str(rc_path)

    return result


def uninstall_completions(shell: Optional[str] = None) -> dict:
    """Remove installed completion scripts.

    Args:
        shell: Shell name. Removes all if None.

    Returns:
        dict: Uninstall result.
    """
    shells = [shell] if shell else list(SUPPORTED_SHELLS)
    removed = []

    for s in shells:
        path = INSTALL_PATHS.get(s)
        if path and path.exists():
            path.unlink()
            removed.append(str(path))

    return {
        "success": True,
        "removed": removed,
        "note": "Source lines in RC files were not removed — do this manually if needed.",
    }
