#!/usr/bin/env python3
"""Publish to PyPI, MCP Registry, and Smithery with proper error handling.

Skips registries where the version is already published.
Fails on auth errors, network issues, or other real problems.
"""

import os
import subprocess
import sys


ALREADY_PUBLISHED_PATTERNS = [
    "already exists",
    "conflict",
    "file already exists",
    "409",
    "400",
    "already published",
]

AUTH_FAILURE_PATTERNS = [
    "401",
    "unauthorized",
    "expired",
    "forbidden",
    "403",
]


def run_publish(name: str, cmd: list[str], env: dict[str, str] | None = None) -> bool:
    """Run a publish command. Returns True on success or already-published, False on real failure."""
    full_env = {**os.environ, **(env or {})}
    print(f"\n{'='*60}")
    print(f"Publishing to {name}...")
    print(f"{'='*60}")

    result = subprocess.run(cmd, capture_output=True, text=True, env=full_env)

    if result.returncode == 0:
        print(f"  {name}: published successfully")
        if result.stdout.strip():
            print(result.stdout.strip())
        return True

    combined = (result.stdout + result.stderr).lower()
    if any(pattern in combined for pattern in ALREADY_PUBLISHED_PATTERNS):
        print(f"  {name}: version already published, skipping")
        return True

    if any(p in combined for p in AUTH_FAILURE_PATTERNS):
        print(f"  {name}: FAILED — authentication error")
        if result.stderr.strip():
            print(f"  {result.stderr.strip()}")
        return False

    print(f"  {name}: FAILED (exit code {result.returncode})")
    if result.stdout.strip():
        print(f"  stdout: {result.stdout.strip()}")
    if result.stderr.strip():
        print(f"  stderr: {result.stderr.strip()}")
    return False


def main() -> int:
    token = os.environ.get("OBRIS_MCP_PYPI_TOKEN", "")
    if not token:
        print("Error: OBRIS_MCP_PYPI_TOKEN environment variable is not set")
        return 1

    results = {}

    # 1. Build and publish to PyPI
    subprocess.run(["rm", "-rf", "dist/"], check=True)
    subprocess.run(["uv", "build"], check=True)

    results["PyPI"] = run_publish(
        "PyPI",
        ["uv", "publish"],
        env={"UV_PUBLISH_PASSWORD": token},
    )

    # 2. MCP Registry via mcp-publisher
    results["MCP Registry"] = run_publish(
        "MCP Registry",
        ["mcp-publisher", "publish"],
    )

    # 3. Smithery
    results["Smithery"] = run_publish(
        "Smithery",
        [
            "smithery", "mcp", "publish", "https://mcp.obris.ai/",
            "-n", "@obris/obris-mcp",
            "--config-schema", '{"type":"object","properties":{}}',
        ],
    )

    # Summary
    print(f"\n{'='*60}")
    print("Publish summary:")
    print(f"{'='*60}")
    failures = []
    for name, ok in results.items():
        status = "ok" if ok else "FAILED"
        print(f"  {name}: {status}")
        if not ok:
            failures.append(name)

    if failures:
        print(f"\nFailed: {', '.join(failures)}")
        return 1

    print("\nAll registries published successfully.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
