import os
from nova_cli.local.file_manager.git_ops import repo


def validate_path(filepath: str) -> str:
    """
    Security Barrier: Ensures the target path is within the current working directory.
    Prevents directory traversal attacks (e.g. ../../../etc/passwd).
    """
    cwd = os.path.abspath(os.getcwd())
    target = os.path.abspath(filepath)

    if os.path.commonpath([cwd, target]) != cwd:
        if repo and repo.working_dir:
            if os.path.commonpath([repo.working_dir, target]) == repo.working_dir:
                return target
        raise PermissionError(
            f"SECURITY ALERT: Access denied. Cannot access '{filepath}' outside project root."
        )

    return target


def resolve_path(filepath: str) -> str:
    """
    Resolves a filepath. 
    1. Prioritizes the current working directory (CWD).
    2. If not found in CWD, searches relative to the Git Root.
    3. Defaults to CWD absolute path for new files.
    """
    # Normalize path separators
    filepath = filepath.replace("\\", "/")
    
    # 1. Check relative to current working directory
    # This ensures if we are in 'Playground/', 'crypto/app.py' becomes 'Playground/crypto/app.py'
    cwd_path = os.path.abspath(filepath)
    if os.path.exists(cwd_path):
        return cwd_path

    # 2. Check relative to Git Root (only if file exists there)
    # This helps find files if the AI uses root-relative paths while we are in a subfolder.
    if repo and repo.working_dir:
        root_path = os.path.abspath(os.path.join(repo.working_dir, filepath))
        if os.path.exists(root_path):
            return root_path

    # 3. Fallback: Return path relative to CWD (for new file creation)
    return cwd_path
