"""
File Type Detection Helper - Unified logic for detecting files vs folders

This module provides a single source of truth for determining whether a path
represents a file or a folder across the entire project.
"""

import os
import re
from typing import Optional


def is_folder_path(file_path: str, file_name: Optional[str] = None) -> bool:
    """
    Determine if a path represents a folder (not a file).
    
    Logic:
    1. If path ends with '/' → definitely a folder
    2. If path has no file extension (e.g., .psd, .jpg) → folder
    3. Otherwise → file
    
    Args:
        file_path: Full path on NAS (e.g., "/Comic_TMS_L/DKI/DE/펀치/001.psd")
        file_name: Optional file name for validation
        
    Returns:
        True if folder, False if file
        
    Examples:
        >>> is_folder_path("/path/to/file.psd")
        False
        
        >>> is_folder_path("/path/to/[식자설정]")
        True
        
        >>> is_folder_path("/path/to/folder/")
        True
        
        >>> is_folder_path("/path/to/DE_PSD")
        True
    """
    if not file_path:
        return False
    
    # Explicit folder marker
    if file_path.endswith('/'):
        return True
    
    # Check if path has file extension
    # Pattern: .extension at end (excluding / in extension)
    # This handles: .psd, .jpg, .zip, .psb, .png, etc.
    has_extension = bool(re.search(r'\.[^/.]+$', file_path))
    
    # No extension = folder
    return not has_extension


def should_add_zip_extension(file_path: str, file_name: str) -> bool:
    """
    Determine if .zip extension should be added for download.
    
    NAS API automatically zips folders, so we need to add .zip to the destination
    filename when downloading folders.
    
    Args:
        file_path: Full path on NAS
        file_name: Current file name
        
    Returns:
        True if should add .zip extension
        
    Examples:
        >>> should_add_zip_extension("/path/[식자설정]", "[식자설정]")
        True
        
        >>> should_add_zip_extension("/path/file.psd", "file.psd")
        False
        
        >>> should_add_zip_extension("/path/[식자설정]", "[식자설정].zip")
        False  # Already has .zip
    """
    # Only add .zip if:
    # 1. Path is a folder
    # 2. Name doesn't already have .zip
    return is_folder_path(file_path) and not file_name.endswith('.zip')


def get_download_filename(file_path: str, file_name: str) -> str:
    """
    Get the final filename for download (with .zip if needed).
    
    Args:
        file_path: Full path on NAS
        file_name: Original file name
        
    Returns:
        Final filename for download
        
    Examples:
        >>> get_download_filename("/path/[식자설정]", "[식자설정]")
        "[식자설정].zip"
        
        >>> get_download_filename("/path/file.psd", "file.psd")
        "file.psd"
    """
    if should_add_zip_extension(file_path, file_name):
        return f"{file_name}.zip"
    return file_name
