"""
Tier 3: E2B Sandbox integration via Xenfra API.

The sandbox runs on Xenfra's servers, not locally. Users don't need:
- E2B package installed
- E2B_API_KEY set
- Any E2B configuration

They just need a Xenfra account. We handle E2B on our backend.
"""

from pathlib import Path
from typing import Optional
from dataclasses import dataclass

from .base import BuildPlan


@dataclass
class SandboxResult:
    """Result of sandbox build validation."""
    success: bool
    build_output: str = ""
    error_message: Optional[str] = None
    build_time_seconds: float = 0.0
    
    def __bool__(self):
        return self.success


class E2BSandbox:
    """
    E2B Sandbox client - calls Xenfra API to run sandbox.
    
    The actual sandbox runs on Xenfra's servers using E2B.
    This class just makes API calls to our backend via SDK.
    """
    
    def __init__(self, api_client=None):
        self.api_client = api_client
    
    @property
    def is_available(self) -> bool:
        """Check if sandbox is available (has API client)."""
        return self.api_client is not None
    
    def validate_build(
        self, 
        project_path: Path, 
        plan: BuildPlan,
        file_manifest: list,
        timeout: int = 300
    ) -> SandboxResult:
        """
        Validate a build via Xenfra API sandbox.
        
        Args:
            project_path: Path to the project directory (for reference)
            plan: BuildPlan with build information
            file_manifest: List of file info dicts for the project
            timeout: Maximum time to wait
            
        Returns:
            SandboxResult with build status
        """
        if not self.api_client:
            return SandboxResult(
                success=False,
                error_message="Not authenticated. Run 'xenfra auth login' first."
            )
        
        try:
            # Use SDK's build.validate method
            result = self.api_client.build.validate(
                file_manifest=file_manifest,
                build_plan=plan.to_dict(),
                timeout=timeout
            )
            
            return SandboxResult(
                success=result.get("success", False),
                build_output=result.get("output", ""),
                error_message=result.get("error"),
                build_time_seconds=result.get("build_time", 0.0)
            )
            
        except Exception as e:
            return SandboxResult(
                success=False,
                error_message=f"Sandbox validation failed: {e}"
            )


def get_sandbox(api_client=None) -> E2BSandbox:
    """Get E2B sandbox client."""
    return E2BSandbox(api_client)


def is_sandbox_available(api_client=None) -> bool:
    """Check if sandbox is available."""
    return get_sandbox(api_client).is_available
