"""Shared context resolution logic for CLI commands."""
from __future__ import annotations

import os
from typing import Optional

from k4s.cli.state import CliState
from k4s.core.context_store import Context


def resolve_target(state: CliState, context_name: Optional[str]) -> Context:
    """Resolve a context name to a VM Context object.

    - ``'local'`` is a built-in shortcut for localhost execution.
    - ``None`` falls back to the current context (set via ``k4s context use-context``
      or ``k4s context add ... --current``).

    Raises ValueError if the resolved context is not a VM context.
    """
    if context_name and context_name.lower() == "local":
        return Context(name="local", host="localhost")

    # state.contexts.resolve(None) returns the current context.
    c = state.contexts.resolve(context_name)
    if c.type != "vm":
        raise ValueError(
            f"Context '{c.name}' is type '{c.type}', but this command requires a 'vm' context.\n"
            "  Add one:  k4s context add <name> --host <ip> --username <user> -i <key>"
        )
    if not c.host:
        raise ValueError(f"Context '{c.name}' has no host configured.")
    return c


def resolve_k8s_target(state: CliState, context_name: Optional[str]) -> Context:
    """Resolve a context name to a Kubernetes Context, validating type.

    Returns the resolved Context with a guaranteed kubeconfig path (either
    explicitly set or derived from ``~/.kube/config`` when only
    ``kubectl_context`` is provided).

    Raises ValueError if the resolved context is not a k8s context or has no
    kubeconfig/kubectl-context configured.
    """
    c = state.contexts.resolve(context_name)
    if c.type != "k8s":
        raise ValueError(
            f"Context '{c.name}' is type '{c.type}', but this command requires a 'k8s' context.\n"
            "  Add one:  k4s context add <name> --type k8s --kubeconfig <path>\n"
            "  Or set:   k4s context use-context <k8s-context-name>"
        )
    if not c.kubeconfig and not c.kubectl_context:
        raise ValueError(f"K8s context '{c.name}' has no kubeconfig or kubectl-context configured.")
    return c


def kubeconfig_path_for(c: Context) -> str:
    """Return the effective kubeconfig file path for a k8s context.

    If the context specifies an explicit ``kubeconfig`` path, that is used.
    Otherwise falls back to ``~/.kube/config`` (the kubectl default).
    """
    if c.kubeconfig:
        return c.kubeconfig
    return os.path.expanduser("~/.kube/config")
