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

MCP_DIR = Path.home() / "worksmart-mcp"
MCP_CLIENT_URL = "https://xo-mcp-clients.s3.us-east-1.amazonaws.com/user-summaries-mcp-client.zip"

def setup_mcp_directory():
    """Create and return the MCP directory."""
    MCP_DIR.mkdir(parents=True, exist_ok=True)
    return MCP_DIR

def download_and_extract(token):
    """Download and extract the MCP client."""
    # Download the zip file
    response = requests.get(MCP_CLIENT_URL)
    response.raise_for_status()
    
    with tempfile.NamedTemporaryFile(suffix='.zip', delete=False) as tmp_file:
        tmp_file.write(response.content)
        zip_path = tmp_file.name

    # Clean up existing files
    if (MCP_DIR / "user-summaries-mcp-client").exists():
        shutil.rmtree(MCP_DIR / "user-summaries-mcp-client")
    
    # Extract the zip file
    shutil.unpack_archive(zip_path, MCP_DIR)
    os.unlink(zip_path)  # Clean up the zip file
    
    # Run the script with the token
    script_path = MCP_DIR / "user-summaries-mcp-client" / "script.sh"
    script_path.chmod(0o755)  # Make executable
    subprocess.run([str(script_path), "--token", token], check=True)

@click.command()
@click.option('--token', prompt='Please enter your token', help='Your MCP authentication token')
def main(token):
    """Configure and set up the MCP client."""
    click.echo("Installing WorkSmart MCP...")
    
    try:
        setup_mcp_directory()
        download_and_extract(token)
        click.echo(click.style("MCP installation complete!", fg="green"))
    except Exception as e:
        click.echo(click.style(f"Error: {str(e)}", fg="red"))
        raise click.Abort()

if __name__ == '__main__':
    main()
