#!/usr/bin/env python3
"""
Reserve package names on PyPI by uploading minimal packages.

This ensures we can claim these names before officially migrating.
"""

import os
import shutil
import subprocess
import tempfile
from pathlib import Path

PACKAGES_TO_RESERVE = {
    "mithril-ai": {
        "description": "GPU compute platform for AI/ML workloads - Alternative name for flow-sdk",
        "keywords": ["gpu", "ai", "ml", "compute", "mithril", "flow"],
    },
    "flow-acc": {
        "description": "GPU compute accelerator - Alternative name for flow-sdk", 
        "keywords": ["gpu", "accelerator", "compute", "flow", "ml"],
    },
}

MINIMAL_SETUP = """
from setuptools import setup

setup(
    name="{name}",
    version="0.0.1",
    description="{description}",
    long_description="This package name is reserved. Please install `flow-sdk` instead:\\n\\n```bash\\npip install flow-sdk\\n```\\n\\nFor more information, visit https://github.com/mlfoundry/flow-sdk",
    long_description_content_type="text/markdown",
    author="Foundry Technologies, Inc.",
    author_email="support@mlfoundry.com",
    url="https://github.com/mlfoundry/flow-sdk",
    keywords={keywords},
    classifiers=[
        "Development Status :: 1 - Planning",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: Apache Software License",
        "Programming Language :: Python :: 3",
    ],
    python_requires=">=3.8",
    install_requires=["flow-sdk>=2.0.0"],
)
"""

def create_package(name: str, config: dict, output_dir: Path):
    """Create a minimal package for reservation."""
    pkg_dir = output_dir / name
    pkg_dir.mkdir(exist_ok=True)
    
    # Create setup.py
    setup_content = MINIMAL_SETUP.format(
        name=name,
        description=config["description"],
        keywords=config["keywords"],
    )
    (pkg_dir / "setup.py").write_text(setup_content)
    
    # Create README
    readme = f"""# {name}

This package name is reserved. Please install `flow-sdk` instead:

```bash
pip install flow-sdk
```

For more information, visit [flow-sdk on GitHub](https://github.com/mlfoundry/flow-sdk).
"""
    (pkg_dir / "README.md").write_text(readme)
    
    # Create package directory
    pkg_module = pkg_dir / name.replace("-", "_")
    pkg_module.mkdir(exist_ok=True)
    (pkg_module / "__init__.py").write_text('__version__ = "0.0.1"\\n')
    
    return pkg_dir

def build_package(pkg_dir: Path):
    """Build the package."""
    subprocess.run(["python", "-m", "build"], cwd=pkg_dir, check=True)
    return list(pkg_dir.glob("dist/*.whl"))[0]

def main():
    """Reserve package names."""
    print("Package Name Reservation Tool")
    print("=" * 50)
    
    with tempfile.TemporaryDirectory() as tmpdir:
        output_dir = Path(tmpdir)
        
        for name, config in PACKAGES_TO_RESERVE.items():
            print(f"\\nPreparing {name}...")
            
            # Create package
            pkg_dir = create_package(name, config, output_dir)
            print(f"  ✓ Created package structure")
            
            # Build package
            wheel = build_package(pkg_dir)
            print(f"  ✓ Built wheel: {wheel.name}")
            
            print(f"  → To upload: twine upload {wheel}")
    
    print("\\n" + "=" * 50)
    print("Next steps:")
    print("1. Set up PyPI API tokens")
    print("2. Run: pip install twine")
    print("3. For each package above, run the twine upload command")
    print("4. Or use: twine upload --repository testpypi <wheel> (for testing)")

if __name__ == "__main__":
    main()