"""Update Hugging Face Space using git commands."""

import os
import subprocess
import logging
from pathlib import Path
import shutil
from huggingface_hub import HfApi
from dotenv import load_dotenv

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def run_command(command, cwd=None):
    """Run a shell command and log output."""
    try:
        result = subprocess.run(
            command,
            shell=True,
            check=True,
            text=True,
            capture_output=True,
            cwd=cwd
        )
        logger.info(f"Command output: {result.stdout}")
        return True
    except subprocess.CalledProcessError as e:
        logger.error(f"Command failed: {e.stderr}")
        return False

def update_space():
    """Update the Hugging Face Space using git commands."""
    try:
        # Load environment variables
        load_dotenv()
        token = os.getenv("HUGGINGFACE_TOKEN")
        if not token:
            raise ValueError("HUGGINGFACE_TOKEN not found in environment variables")

        # Space configuration
        SPACE_NAME = "nananie143/agentic-system"
        REPO_URL = f"https://huggingface.co/spaces/{SPACE_NAME}"
        
        logger.info("Starting Space update process...")
        
        # 1. Initialize Hugging Face API
        api = HfApi(token=token)
        
        # 2. Create the Space if it doesn't exist
        logger.info("Creating/Checking Space...")
        try:
            api.create_repo(
                repo_id=SPACE_NAME,
                repo_type="space",
                space_sdk="gradio",
                private=False,
                exist_ok=True
            )
        except Exception as e:
            logger.warning(f"Note about Space creation: {e}")
        
        # 3. Set up the repository directory
        repo_dir = Path("space_repo")
        if repo_dir.exists():
            logger.info("Cleaning up existing repository...")
            shutil.rmtree(repo_dir)
        
        # 4. Clone the Space repository with token
        logger.info("Cloning Space repository...")
        clone_url = f"https://user:{token}@huggingface.co/spaces/{SPACE_NAME}"
        run_command(f"git clone {clone_url} {repo_dir}")
        
        # 5. Copy files to the repository
        logger.info("Copying files to repository...")
        files_to_copy = [
            "app.py",
            "agentic_system.py",
            "requirements.txt",
            "space.yml",
            "download_models_space.py",
            "app_space.sh",
            "reasoning",
            "orchestrator.py",
            "team_management.py",
            "meta_learning.py",
            "config.py"
        ]
        
        for file in files_to_copy:
            src = Path(file)
            dst = repo_dir / src.name
            if src.is_file():
                shutil.copy2(src, dst)
            elif src.is_dir():
                if dst.exists():
                    shutil.rmtree(dst)
                shutil.copytree(src, dst)
        
        # 6. Configure git
        logger.info("Configuring git...")
        run_command('git config user.email "cascade@codeium.com"', cwd=repo_dir)
        run_command('git config user.name "Cascade Bot"', cwd=repo_dir)
        
        # 7. Add and commit changes
        logger.info("Committing changes...")
        run_command("git add .", cwd=repo_dir)
        run_command('git commit -m "Update Space with latest changes and model configurations"', cwd=repo_dir)
        
        # 8. Push changes
        logger.info("Pushing changes to Space...")
        run_command("git push", cwd=repo_dir)
        
        # 9. Clean up
        logger.info("Cleaning up...")
        shutil.rmtree(repo_dir)
        
        logger.info(f"Space updated successfully! Visit: {REPO_URL}")
        return True
        
    except Exception as e:
        logger.error(f"Error updating Space: {e}")
        return False

if __name__ == "__main__":
    update_space()