"""
This module handles file type validation and encryption state detection.
It ensures that only non-programming and non-system files are processed,
and identifies if a file is already encrypted by checking for a specific magic marker.
"""

import pathlib
from typing import Tuple

# Magic marker to identify encrypted files
MAGIC_MARKER = b"FVLT"

# Files that are explicitly allowed for encryption
SUPPORTED_EXTENSIONS = {
    ".txt", ".md", ".csv", ".log", ".pdf", ".docx", ".odt",
    ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".webp",
    ".mp3", ".wav", ".flac", ".ogg", ".mp4", ".mov", ".avi",
    ".mkv", ".zip"
}

# Files that must NEVER be encrypted
BLOCKED_EXTENSIONS = {
    ".py", ".js", ".ts", ".html", ".css", ".sh", ".bat", ".exe",
    ".bin", ".json", ".yaml", ".toml", ".ini", ".env", ".db", ".sqlite"
}


def is_encrypted(filepath: str) -> bool:
    """
    Checks if a file is currently encrypted by reading its first 4 bytes
    for the 'FVLT' magic marker.

    Args:
        filepath (str): The path to the file to check.

    Returns:
        bool: True if the file starts with the FVLT marker, False otherwise.
    """
    path = pathlib.Path(filepath)
    if not path.is_file():
        return False

    try:
        with open(path, "rb") as f:
            header = f.read(len(MAGIC_MARKER))
            return header == MAGIC_MARKER
    except (IOError, OSError):
        return False


def is_supported(filepath: str) -> Tuple[bool, str]:
    """
    Determines if a file is allowed to be encrypted or decrypted.
    Checks the file extension against supported and blocked lists.

    Args:
        filepath (str): The path to the file to validate.

    Returns:
        Tuple[bool, str]: A tuple containing (is_supported, reason).
                          Reason is an empty string if supported.
    """
    path = pathlib.Path(filepath)

    if not path.exists():
        return False, f"File not found: {filepath}"

    if not path.is_file():
        return False, f"Path is not a file: {filepath}"

    # Normalize extension to lowercase including the dot
    ext = path.suffix.lower()

    if ext in BLOCKED_EXTENSIONS:
        return False, f"Files with '{ext}' extension are protected and cannot be encrypted."

    if ext not in SUPPORTED_EXTENSIONS:
        return False, f"Extension '{ext}' is not supported by File Vault."

    # Additional check: If it's already encrypted, it's 'supported' in the sense
    # that the tool can interact with it (for decryption), but the caller
    # should use is_encrypted() to decide which operation to perform.
    return True, ""
