# Copyright 2026 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""CLI error handling utilities."""

from typing import Callable, Optional

from huggingface_hub.errors import (
    BucketNotFoundError,
    GatedRepoError,
    HfHubHTTPError,
    LocalTokenNotFoundError,
    RemoteEntryNotFoundError,
    RepositoryNotFoundError,
    RevisionNotFoundError,
)


def _format_repo_not_found(error: RepositoryNotFoundError) -> str:
    label = error.repo_type.capitalize() if error.repo_type else "Repository"
    if error.repo_id:
        msg = f"{label} '{error.repo_id}' not found."
    else:
        msg = f"{label} not found."
    msg += " If the repo is private, make sure you are authenticated."
    return msg


def _format_gated_repo(error: GatedRepoError) -> str:
    label = error.repo_type if error.repo_type else "repository"
    if error.repo_id:
        return f"Access denied. {label.capitalize()} '{error.repo_id}' requires approval."
    return f"Access denied. This {label} requires approval."


def _format_bucket_not_found(error: BucketNotFoundError) -> str:
    if error.bucket_id:
        return f"Bucket '{error.bucket_id}' not found. If the bucket is private, make sure you are authenticated."
    return "Bucket not found. Check the bucket id (namespace/name). If the bucket is private, make sure you are authenticated."


def _format_entry_not_found(error: RemoteEntryNotFoundError) -> str:
    label = error.repo_type if error.repo_type else "repository"
    url = str(error.response.url) if error.response else None
    if error.repo_id:
        msg = f"File not found in {label} '{error.repo_id}'."
    else:
        msg = f"File not found in {label}."
    if url:
        msg += f"\nURL: {url}"
    return msg


def _format_revision_not_found(error: RevisionNotFoundError) -> str:
    label = error.repo_type if error.repo_type else "repository"
    if error.repo_id:
        return f"Revision not found in {label} '{error.repo_id}'."
    return f"Revision not found in {label}. Check the revision parameter."


CLI_ERROR_MAPPINGS: dict[type[Exception], Callable[[Exception], str]] = {  # type: ignore
    # GatedRepoError must come before RepositoryNotFoundError (it's a subclass).
    GatedRepoError: _format_gated_repo,  # type: ignore[dict-item]
    BucketNotFoundError: _format_bucket_not_found,  # type: ignore[dict-item]
    RepositoryNotFoundError: _format_repo_not_found,  # type: ignore[dict-item]
    RevisionNotFoundError: _format_revision_not_found,  # type: ignore[dict-item]
    LocalTokenNotFoundError: lambda _: "Not logged in. Run 'hf auth login' first.",
    RemoteEntryNotFoundError: _format_entry_not_found,  # type: ignore[dict-item]
    HfHubHTTPError: lambda error: str(error),
    ValueError: lambda error: f"Invalid value. {error}",
}


def format_known_exception(error: Exception) -> Optional[str]:
    for exc_type, formatter in CLI_ERROR_MAPPINGS.items():
        if isinstance(error, exc_type):
            return formatter(error)
    return None
