"""
PyPI publisher.
Builds and uploads a Python PoC package using twine.
"""

from __future__ import annotations

import logging
import subprocess
import sys
from pathlib import Path

logger = logging.getLogger(__name__)


def publish(poc_dir: Path, token: str, simulate: bool = False) -> bool:
    """
    Build and upload a Python PoC package to PyPI.

    Args:
        poc_dir:  Path to the PoC package directory (must contain setup.py).
        token:    PyPI API token (starts with 'pypi-').
        simulate: If True, build but do not upload.

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

    # Build
    logger.info(f"Building PyPI package: {poc_dir.name}")
    result = subprocess.run(
        [sys.executable, "setup.py", "sdist", "bdist_wheel"],
        cwd=poc_dir,
        capture_output=True,
        text=True,
    )
    if result.returncode != 0:
        logger.error(f"Build failed:\n{result.stderr}")
        return False

    if simulate:
        logger.info("[SIMULATE] Skipping upload to PyPI.")
        return True

    # Upload
    logger.info(f"Uploading {poc_dir.name} to PyPI …")
    upload = subprocess.run(
        ["twine", "upload", "dist/*", "--username", "__token__", "--password", token],
        cwd=poc_dir,
        capture_output=True,
        text=True,
    )
    if upload.returncode != 0:
        logger.error(f"Upload failed:\n{upload.stderr}")
        return False

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