import logging
import os
from typing import Union
from uuid import UUID

from acelerai_pipelines.models.process_status import ProcessStatusType

logger = logging.getLogger("PipelinesUtils")


def toUpperFirst(s: str) -> str:
    """
    Capitalizes the first character of a string.
    """
    if not s:
        return s
    return s[0].upper() + s[1:]


def validate_process_status_params(
    status: Union[ProcessStatusType, str],
    process_name: str,
    title: str,
) -> tuple[str, str, str, str]:
    """
    Validates and standardizes the parameters for sending a ProcessStatus.
    Returns (status_val, process_name, title, run_id_str).
    Raises ValueError on validation failures.
    """
    process_name = str(process_name).strip() if process_name is not None else ""
    if not process_name or len(process_name) > 200:
        err_msg = (
            f"process_name is mandatory and cannot be empty. "
            f"Max length is 200 characters (length: {len(process_name)})."
        )
        logger.error(err_msg)
        raise ValueError(err_msg)

    title = str(title).strip() if title is not None else ""
    if not title or len(title) > 200:
        err_msg = (
            f"title is mandatory and cannot be empty. "
            f"Max length is 200 characters (length: {len(title)})."
        )
        logger.error(err_msg)
        raise ValueError(err_msg)

    if isinstance(status, ProcessStatusType):
        status_val = status.value
    else:
        try:
            status_val = ProcessStatusType(status).value
        except ValueError:
            err_msg = (
                f"Invalid status: {status}. "
                f"Must be one of {[e.value for e in ProcessStatusType]}."
            )
            logger.error(err_msg)
            raise ValueError(err_msg)

    run_id = os.environ.get("RUN_ID")
    if not run_id:
        err_msg = "RUN_ID environment variable must be set."
        logger.error(err_msg)
        raise ValueError(err_msg)

    try:
        run_uuid = UUID(str(run_id))
    except ValueError:
        err_msg = f"Invalid RUN_ID: {run_id}. Must be a valid UUID."
        logger.error(err_msg)
        raise ValueError(err_msg)

    return status_val, process_name, title, str(run_uuid)
