"""Model push to HuggingFace Hub."""

from __future__ import annotations

import logging
from pathlib import Path

logger = logging.getLogger(__name__)


class ModelPusher:
    """Push trained models to HuggingFace Hub."""

    def __init__(self, token: str | None = None) -> None:
        self._api = None
        self._token = token

    def _get_api(self):
        """Lazy-load huggingface_hub API."""
        if self._api is None:
            try:
                from huggingface_hub import HfApi

                self._api = HfApi(token=self._token)
            except ImportError:
                raise ImportError(
                    "huggingface_hub is required for push features. "
                    "Install with: pip install huggingface-hub"
                ) from None
        return self._api

    def push_model(
        self,
        model_dir: str | Path,
        repo_id: str,
        commit_message: str = "Upload model via BilgeAI",
        private: bool = False,
    ) -> str:
        """Push a trained model directory to HuggingFace Hub.

        Returns the URL of the uploaded model.
        """
        model_dir = Path(model_dir)
        if not model_dir.exists():
            raise FileNotFoundError(f"Model directory not found: {model_dir}")

        api = self._get_api()

        # Create repo if it doesn't exist
        api.create_repo(repo_id=repo_id, exist_ok=True, private=private)

        # Upload the entire directory
        api.upload_folder(
            folder_path=str(model_dir),
            repo_id=repo_id,
            commit_message=commit_message,
        )

        url = f"https://huggingface.co/{repo_id}"
        logger.info("Model pushed to %s", url)
        return url

    def push_file(
        self,
        file_path: str | Path,
        repo_id: str,
        path_in_repo: str | None = None,
        commit_message: str = "Upload file via BilgeAI",
    ) -> str:
        """Push a single file to an existing HuggingFace repo."""
        file_path = Path(file_path)
        if not file_path.exists():
            raise FileNotFoundError(f"File not found: {file_path}")

        api = self._get_api()

        if path_in_repo is None:
            path_in_repo = file_path.name

        api.upload_file(
            path_or_fileobj=str(file_path),
            path_in_repo=path_in_repo,
            repo_id=repo_id,
            commit_message=commit_message,
        )

        url = f"https://huggingface.co/{repo_id}"
        logger.info("File pushed to %s", url)
        return url
