import os
import requests
from .config import load_config
from .repo_utils import zip_repo

class MCPClient:
    """
    Client for interacting with the CodedThemes MCP Server.
    """
    def __init__(self):
        config = load_config()
        self.server_url = (
            os.getenv("CODEDTHEMES_SERVER")
            or config.get("server_url")
            or "https://mcp.codedthemes.com"
        ).rstrip("/")
        self.token = config.get("access_token")

    def upload_workspace(self, repo_path: str, user_id: str):
        """
        Zips and uploads the repository to create a new workspace.
        """
        zip_path = zip_repo(repo_path)
        repo_name = os.path.basename(repo_path)
        
        headers = {}
        if self.token:
            headers["Authorization"] = f"Bearer {self.token}"

        try:
            with open(zip_path, 'rb') as f:
                files = {'file': (f"{repo_name}.zip", f, 'application/zip')}
                data = {'user_id': user_id, 'repo_name': repo_name}
                
                response = requests.post(
                    f"{self.server_url}/workspaces",
                    data=data,
                    files=files,
                    headers=headers,
                    timeout=300
                )
                
                if response.status_code == 413:
                    zip_size_mb = os.path.getsize(zip_path) / (1024 * 1024)
                    raise Exception(
                        f"Upload failed: File is too large (413). Zip size: {zip_size_mb:.1f} MB.\n"
                        "  Please reduce your repository size:\n"
                        "  • Add large files/folders to .gitignore\n"
                        "  • Remove binary assets (images, videos, fonts)\n"
                        "  • Delete unused dependencies"
                    )
                
                if response.status_code != 200:
                    raise Exception(f"Upload failed: {response.status_code} - {response.text}")
                
                return response.json()
        finally:
            if os.path.exists(zip_path):
                os.remove(zip_path)

    def call(self, tool_name: str, payload: dict):
        """
        Calls a remote MCP tool or the login endpoint.
        """
        headers = {}
        if self.token:
            headers["Authorization"] = f"Bearer {self.token}"

        # Login and Logout use dedicated endpoints
        if tool_name == "login":
            url = f"{self.server_url}/auth/login"
        elif tool_name == "logout":
            url = f"{self.server_url}/auth/logout"
        else:
            url = f"{self.server_url}/tools/{tool_name}"


        response = requests.post(
            url,
            json=payload,
            headers=headers,
            timeout=300
        )

        if response.status_code == 401:
            raise Exception("Unauthorized. Please run 'codedthemes login'.")

        if response.status_code != 200:
            raise Exception(f"Server error: {response.status_code} - {response.text}")

        return response.json()
