"""Upgrade utilities for dotpromptz."""

from __future__ import annotations

import subprocess

from dotpromptz.errors import UpgradeError
from dotpromptz.logging import get_logger

logger = get_logger(__name__)

_PYPI_PACKAGE_NAME = 'dotpromptz-py'


def run_upgrade() -> int:
    """Upgrade ``dotpromptz-py`` via ``uv tool upgrade``.

    Returns:
        Process exit code.

    Raises:
        UpgradeError: If ``uv`` is not available.
    """
    cmd = ['uv', 'tool', 'upgrade', _PYPI_PACKAGE_NAME]
    logger.info('Running upgrade command.', command=' '.join(cmd))
    try:
        result = subprocess.run(cmd, check=False)  # noqa: S603
    except FileNotFoundError as exc:
        raise UpgradeError(
            'uv not found. Please install uv first: https://docs.astral.sh/uv/',
            code='upgrade_uv_missing',
        ) from exc
    return result.returncode
