"""Claude Code session management.

Claude Code sessions use the "cc" tag in their session name:
    gpu01-vajra-cc-20260212-143022
"""

import os
import shutil

from .config import CC_TAG
from .env_detect import DetectedEnv
from .naming import get_dir_pattern
from .session import auto_connect, create_session, list_sessions
from .utils import only_cc_sessions

CLAUDE_CODE_CMD_ENV = "CLAUDE_CODE_CMD"
DEFAULT_CLAUDE_CMD = "claude"


def get_claude_cmd() -> str:
    """Get Claude Code command. Check env var, then PATH."""
    cmd = os.environ.get(CLAUDE_CODE_CMD_ENV, DEFAULT_CLAUDE_CMD)
    if not shutil.which(cmd):
        raise FileNotFoundError(
            f"Claude Code not found: '{cmd}'\n"
            f"  Install: npm install -g @anthropic-ai/claude-code\n"
            f"  Or set:  export {CLAUDE_CODE_CMD_ENV}=/path/to/claude"
        )
    return cmd


def _build_claude_cmd(
    extra_args: str | None = None,
    config_dir: str | None = None,
) -> str:
    """Build the full claude command with optional config dir and extra args."""
    parts = []
    if config_dir:
        expanded = os.path.expanduser(config_dir)
        parts.append(f"CLAUDE_CONFIG_DIR={expanded}")
    parts.append(get_claude_cmd())
    if extra_args:
        parts.append(extra_args)
    return " ".join(parts)


def launch_cc(
    env: DetectedEnv | None = None,
    extra_args: str | None = None,
    config_dir: str | None = None,
) -> None:
    """Launch Claude Code in a new named screen session."""
    full_cmd = _build_claude_cmd(extra_args=extra_args, config_dir=config_dir)
    create_session(tag=CC_TAG, env=env, extra_command=full_cmd)


def auto_connect_cc(
    env: DetectedEnv | None = None,
    config_dir: str | None = None,
) -> None:
    """Auto-connect to latest Claude Code session globally."""
    full_cmd = _build_claude_cmd(config_dir=config_dir)
    auto_connect(pattern=None, create_tag=CC_TAG, env=env, extra_command=full_cmd, cc_only=True)


def auto_connect_cc_dir(
    env: DetectedEnv | None = None,
    config_dir: str | None = None,
) -> None:
    """Auto-connect to latest Claude Code session in current dir."""
    pattern = get_dir_pattern(tag_filter=CC_TAG)
    full_cmd = _build_claude_cmd(config_dir=config_dir)
    auto_connect(pattern=pattern, create_tag=CC_TAG, env=env, extra_command=full_cmd)


def list_cc_sessions_dir() -> list[dict]:
    """List Claude Code sessions for current dir."""
    pattern = get_dir_pattern(tag_filter=CC_TAG)
    return list_sessions(pattern=pattern)


def list_all_cc_sessions() -> list[dict]:
    """List all Claude Code sessions globally."""
    return only_cc_sessions(list_sessions())
