#!/usr/bin/env python3
"""
Upload SWE Agent to PyPI using the API token from secrets
"""

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

def setup_pypirc():
    """Set up .pypirc file with API token"""
    pypirc_content = """[distutils]
index-servers = pypi

[pypi]
repository = https://upload.pypi.org/legacy/
username = __token__
password = {token}
""".format(token=os.environ.get('PYPI_API_TOKEN'))
    
    pypirc_path = Path.home() / '.pypirc'
    with open(pypirc_path, 'w') as f:
        f.write(pypirc_content)
    
    # Set proper permissions
    os.chmod(pypirc_path, 0o600)
    print(f"✅ Created .pypirc at {pypirc_path}")

def build_package():
    """Build the package using setuptools"""
    print("🔨 Building package...")
    
    # Clean previous builds
    for dir_name in ["build", "dist", "swe_agent.egg-info"]:
        if os.path.exists(dir_name):
            shutil.rmtree(dir_name)
    
    # Create setup.py for building
    setup_py_content = '''
from setuptools import setup, find_packages
import os

# Read the contents of your README file
this_directory = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(this_directory, 'README.md'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name="swe-ai-agent",
    version="1.0.2",
    author="Harish SG",
    author_email="harishsg993010@gmail.com",
    description="SWE Agent - Headless Agentic IDE with comprehensive tool support",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/harishsg993010/SWE-Agent",
    packages=find_packages(),
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Intended Audience :: Developers",
        "Topic :: Software Development :: Build Tools",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
        "Programming Language :: Python :: 3.11",
        "Programming Language :: Python :: 3.12",
        "Operating System :: OS Independent",
    ],
    python_requires=">=3.9",
    install_requires=[
        "anthropic>=0.57.1",
        "langchain-anthropic>=0.3.17",
        "langchain>=0.3.26",
        "langchain-core>=0.3.68",
        "langgraph>=0.5.3",
        "rich>=14.0.0",
        "click>=8.0.0",
        "psutil>=5.8.0",
        "python-dotenv>=1.0.0",
        "typing-extensions>=4.0.0",
        "pydantic>=2.0.0",
        "requests>=2.28.0",
        "aiohttp>=3.8.0",
    ],
    entry_points={
        "console_scripts": [
            "swe-agent=swe_agent.main:main",
        ],
    },
    include_package_data=True,
    package_data={
        "swe_agent": ["**/*.py"],
    },
)
'''
    
    with open('setup.py', 'w') as f:
        f.write(setup_py_content)
    
    # Build source and wheel distributions
    try:
        subprocess.run([sys.executable, 'setup.py', 'sdist', 'bdist_wheel'], check=True)
        print("✅ Package built successfully!")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ Build failed: {e}")
        return False

def upload_package():
    """Upload the package to PyPI"""
    print("🚀 Uploading to PyPI...")
    
    # Check if dist directory exists
    if not os.path.exists('dist'):
        print("❌ No dist directory found. Build the package first.")
        return False
    
    # Install twine if not available
    try:
        subprocess.run([sys.executable, '-m', 'pip', 'install', 'twine'], check=True, capture_output=True)
    except subprocess.CalledProcessError:
        print("❌ Failed to install twine")
        return False
    
    # Upload to PyPI
    try:
        subprocess.run([sys.executable, '-m', 'twine', 'upload', 'dist/*'], check=True)
        print("✅ Package uploaded successfully to PyPI!")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ Upload failed: {e}")
        return False

def main():
    """Main function"""
    print("📦 SWE Agent PyPI Upload Script")
    print("=" * 40)
    
    # Check for API token
    if not os.environ.get('PYPI_API_TOKEN'):
        print("❌ PYPI_API_TOKEN environment variable not set")
        sys.exit(1)
    
    # Set up .pypirc
    setup_pypirc()
    
    # Build package
    if not build_package():
        sys.exit(1)
    
    # Upload package
    if not upload_package():
        sys.exit(1)
    
    print("\n🎉 Success! SWE Agent is now available on PyPI!")
    print("Users can install it with: pip install swe-agent")
    print("And run it with: swe-agent --help")

if __name__ == "__main__":
    main()