"""App resolution: --app flag → KUBEROKU_APP env → .kuberoku file.

Centralizes the logic for resolving which app a command targets.
Every command that needs an app name calls resolve_app().
"""

from __future__ import annotations

import os

from kuberoku.branding import ENV_PREFIX
from kuberoku.config.project import ProjectLink, resolve_project_link
from kuberoku.exceptions import KuberokuError


class AppResolutionError(KuberokuError):
    """Raised when no app can be resolved."""

    def __init__(self) -> None:
        super().__init__(
            "No app specified. Use --app, set KUBEROKU_APP, "
            "or run 'kuberoku link' in your project directory."
        )


def resolve_app(
    app_flag: str | None = None,
) -> str:
    """Resolve the target app name from the resolution chain.

    Priority:
    1. --app / -a flag (may be an alias or literal name)
    2. KUBEROKU_APP env var
    3. .kuberoku project file (default alias)

    Returns the resolved app name.
    Raises AppResolutionError if no app can be determined.
    """
    if app_flag:
        # Smart resolution: check if it's an alias first
        link = resolve_project_link(alias=app_flag)
        if link:
            return link.app
        # Not an alias — treat as literal app name
        return app_flag

    # Check env var
    env_app = os.environ.get(f"{ENV_PREFIX}APP")
    if env_app:
        return env_app

    # Check .kuberoku project file (default alias)
    link = resolve_project_link()
    if link:
        return link.app

    raise AppResolutionError()


def resolve_app_and_cluster(
    app_flag: str | None = None,
) -> tuple[str, str | None]:
    """Resolve both app name and cluster from the resolution chain.

    Returns (app_name, cluster_name_or_none).
    """
    if app_flag:
        link = resolve_project_link(alias=app_flag)
        if link:
            return link.app, link.cluster
        return app_flag, None

    env_app = os.environ.get(f"{ENV_PREFIX}APP")
    if env_app:
        return env_app, None

    link = resolve_project_link()
    if link:
        return link.app, link.cluster

    raise AppResolutionError()


def resolve_project_link_for_display(
    alias: str | None = None,
) -> ProjectLink | None:
    """Resolve a project link for display purposes. Returns None instead of raising."""
    return resolve_project_link(alias=alias)
