from __future__ import annotations
from pathlib import Path
from typing import Any, Optional
from sibi_flux.core.managed_resource._managed_resource import ManagedResource
from sibi_flux.core.project import ProjectService
from sibi_flux.utils.security import is_secure_path

class SecureResource(ManagedResource):
    """
    Enhanced resource that automatically enforces path sandboxing for all I/O.
    Ensures that all operations remain within the project root to prevent path traversal.
    """
    
    def __init__(self, **kwargs: Any) -> None:
        """
        Initializes the SecureResource.
        Sets the project root for sandboxing context.
        """
        super().__init__(**kwargs)
        # We ensure project root is detected at instantiation for security context
        self.project_root = ProjectService.detect_project_root()

    def get_secure_path(self, path: str | Path) -> Path:
        """
        Validates and resolves a path within the sandboxed project root.
        
        Args:
            path: The path to secure.
            
        Returns:
            Path: The resolved absolute Path object.
            
        Raises:
            PermissionError: If the path is outside the allowed project root.
        """
        resolved = Path(path).resolve()
        if not is_secure_path(resolved, [self.project_root]):
            self.logger.error(
                f"SECURITY VIOLATION: Path traversal attempt detected. "
                f"Target: {path}, Root: {self.project_root}"
            )
            # We raise PermissionError as it is semantically appropriate for sandbox violations
            raise PermissionError(
                f"Access denied: Path {path} is outside the sandboxed project root."
            )
        return resolved

    def open_secure(self, path: str | Path, mode: str = "r", **kwargs: Any):
        """
        Opens a file securely, enforcing sandbox constraints.
        
        Args:
            path: The path to the file.
            mode: The file mode (default 'r').
            **kwargs: Additional arguments for the open() function.
            
        Returns:
            TextIO | BinaryIO: The opened file handle.
        """
        secure_path = self.get_secure_path(path)
        return open(secure_path, mode, **kwargs)

    def write_text_secure(self, path: str | Path, content: str, encoding: str = "utf-8") -> None:
        """
        Writes text to a file securely.
        """
        secure_path = self.get_secure_path(path)
        secure_path.write_text(content, encoding=encoding)

    def read_text_secure(self, path: str | Path, encoding: str = "utf-8") -> str:
        """
        Reads text from a file securely.
        """
        secure_path = self.get_secure_path(path)
        return secure_path.read_text(encoding=encoding)
