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

from __future__ import annotations

import logging
import subprocess
from pathlib import Path

logger = logging.getLogger(__name__)


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

    # Build gem
    result = subprocess.run(["gem", "build", gemspecs[0].name], cwd=poc_dir, capture_output=True, text=True)
    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

    push = subprocess.run(
        ["gem", "push", gems[0].name, "--key", token],
        cwd=poc_dir,
        capture_output=True,
        text=True,
    )
    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
