"""
RubyGems publisher.
Builds and pushes a gem PoC package.
"""

from __future__ import annotations

import logging
import shutil
import subprocess
from pathlib import Path

logger = logging.getLogger(__name__)


def _gem() -> str:
    cmd = shutil.which("gem")
    if not cmd:
        raise FileNotFoundError(
            "gem not found on PATH. Install Ruby to publish RubyGems packages."
        )
    return cmd


def publish(poc_dir: Path, token: str, simulate: bool = False) -> bool:
    """
    Build and push a RubyGem PoC package.

    Args:
        poc_dir:  Path to the PoC package directory (must contain *.gemspec).
        token:    RubyGems API key.
        simulate: If True, build but do not push.

    Returns:
        True on success, False on failure.
    """
    gemspecs = list(poc_dir.glob("*.gemspec"))
    if not gemspecs:
        logger.error(f"No .gemspec found in {poc_dir}")
        return False

    try:
        gem = _gem()
    except FileNotFoundError as exc:
        logger.error(str(exc))
        return False

    # Build gem
    try:
        result = subprocess.run(
            [gem, "build", gemspecs[0].name], cwd=poc_dir, capture_output=True, text=True
        )
    except Exception as exc:
        logger.error(f"gem build error: {exc}")
        return False

    if result.returncode != 0:
        logger.error(f"gem build failed:\n{result.stderr}")
        return False

    if simulate:
        logger.info(f"[SIMULATE] Skipping gem push for {poc_dir.name}.")
        return True

    gems = list(poc_dir.glob("*.gem"))
    if not gems:
        logger.error("No .gem file produced after build.")
        return False

    try:
        push = subprocess.run(
            [gem, "push", gems[0].name, "--key", token],
            cwd=poc_dir,
            capture_output=True,
            text=True,
        )
    except Exception as exc:
        logger.error(f"gem push error: {exc}")
        return False

    if push.returncode != 0:
        logger.error(f"gem push failed:\n{push.stderr}")
        return False

    logger.info(f"Successfully pushed {gems[0].name} to RubyGems.")
    return True
