"""
Hugging Face Spaces Automation Agent
"""
import os
import json
import requests
from pathlib import Path
import time
import base64
import random
import string
from datetime import datetime

class HuggingFaceSpacesAgent:
    def __init__(self, token, username):
        self.token = token
        self.username = username
        self.api_url = "https://huggingface.co/api"
        self.headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json"
        }
        
    def generate_unique_name(self, base_name="test-app"):
        """Generate a unique name for the space"""
        suffixes = [
            "desk", "lab", "hub", "zone", "box", "port", "base", "spot"
        ]
        timestamp = datetime.now().strftime("%m%d")
        random_chars = ''.join(random.choices(string.ascii_lowercase, k=3))
        random_suffix = random.choice(suffixes)
        return f"{base_name}-{random_suffix}-{timestamp}-{random_chars}"

    
    def create_space(self, space_name, framework="gradio"):
        """Create a new Hugging Face Space"""
        # Try to delete existing space first
        self.delete_space(space_name)
        time.sleep(5)  # Wait for deletion to complete
        
        url = f"{self.api_url}/repos/create"
        payload = {
            "type": "space",
            "name": space_name,
            "organization": self.username,
            "private": False,
            "sdk": framework
        }
        
        try:
            response = requests.post(url, headers=self.headers, json=payload)
            response.raise_for_status()
            print(f"Successfully created space: {space_name}")
            print(f"Response: {response.text}")
            return True
        except requests.exceptions.RequestException as e:
            print(f"Failed to create space: {str(e)}")
            if hasattr(e.response, 'text'):
                print(f"Error details: {e.response.text}")
            return False

    def upload_file(self, space_name, file_path, content, branch="main"):
        """Upload a file to the space using the Hugging Face API"""
        url = f"https://huggingface.co/api/spaces/{self.username}/{space_name}/content/{file_path}"
        
        try:
            # Convert content to bytes if it's a string
            content_bytes = content.encode('utf-8') if isinstance(content, str) else content
            
            # Create files payload
            files = {
                'content': ('blob', content_bytes, 'application/octet-stream'),
            }
            
            headers = {"Authorization": f"Bearer {self.token}"}
            
            response = requests.post(url, headers=headers, files=files)
            if response.status_code == 200:
                print(f"Successfully uploaded {file_path}")
                return True
                
            print(f"Failed to upload {file_path}: Status {response.status_code}")
            print(f"Response: {response.text}")
            return False
            
        except Exception as e:
            print(f"Error uploading {file_path}: {str(e)}")
            return False

    def create_dockerfile(self):
        """Create a Dockerfile for the space"""
        return """
FROM python:3.9-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .

EXPOSE 7860

CMD ["python", "app.py"]
"""

    def create_app(self):
        """Create a sample Gradio app"""
        return """
import gradio as gr

def greet(name):
    return f"Hello, {name}!"

# Create the Gradio interface
iface = gr.Interface(
    fn=greet,
    inputs=gr.Textbox(label="Enter your name"),
    outputs=gr.Textbox(label="Greeting"),
    title="Simple Greeting App"
)

# Launch the app
if __name__ == "__main__":
    iface.launch(server_name="0.0.0.0", server_port=7860)
"""

    def create_requirements(self):
        """Create requirements.txt"""
        return "gradio>=3.50.0\n"

    def deploy_sample_space(self, space_name):
        """Deploy a sample space with all necessary files"""
        # First create the space
        if not self.create_space(space_name):
            return False

        # Wait longer for space to be properly initialized
        print("Waiting for space initialization...")
        time.sleep(15)

        # Upload Dockerfile
        dockerfile_content = self.create_dockerfile()
        if not self.upload_file(space_name, "Dockerfile", dockerfile_content):
            return False

        # Upload app.py
        app_content = self.create_app()
        if not self.upload_file(space_name, "app.py", app_content):
            return False

        # Upload requirements.txt
        requirements_content = self.create_requirements()
        if not self.upload_file(space_name, "requirements.txt", requirements_content):
            return False

        print(f"Successfully deployed sample space: {space_name}")
        print(f"You can visit your space at: https://huggingface.co/spaces/{self.username}/{space_name}")
        return True

def main():
    # Initialize the agent with your credentials
    agent = HuggingFaceSpacesAgent(
        token="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",
        username="factorst"
    )
    
    # Generate a unique space name
    space_name = agent.generate_unique_name()
    print(f"Creating new space with name: {space_name}")
    agent.deploy_sample_space(space_name)

if __name__ == "__main__":
    main()