"""
npm publisher.
Publishes a Node.js PoC package using the npm CLI.
"""

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:
    """
    Publish a Node.js PoC package to the npm registry.

    Args:
        poc_dir:  Path to the PoC package directory (must contain package.json).
        token:    npm access token.
        simulate: If True, run 'npm pack' only (no publish).

    Returns:
        True on success, False on failure.
    """
    if not (poc_dir / "package.json").exists():
        logger.error(f"No package.json found in {poc_dir}")
        return False

    if simulate:
        logger.info(f"[SIMULATE] npm pack {poc_dir.name}")
        result = subprocess.run(["npm", "pack"], cwd=poc_dir, capture_output=True, text=True)
        logger.info(result.stdout)
        return result.returncode == 0

    logger.info(f"Publishing {poc_dir.name} to npm …")
    env_patch = {"NPM_TOKEN": token}
    result = subprocess.run(
        ["npm", "publish", "--access", "public"],
        cwd=poc_dir,
        capture_output=True,
        text=True,
        env={**__import__("os").environ, **env_patch},
    )
    if result.returncode != 0:
        logger.error(f"npm publish failed:\n{result.stderr}")
        return False

    logger.info(f"Successfully published {poc_dir.name} to npm.")
    return True
