"""
Helper utility functions for ScholarPress.
"""

import os
import re
from datetime import datetime
from werkzeug.utils import secure_filename
from flask import current_app
import uuid


def allowed_file(filename, allowed_extensions=None):
    """Check if a file has an allowed extension."""
    if allowed_extensions is None:
        allowed_extensions = current_app.config.get('ALLOWED_EXTENSIONS', {'pdf', 'docx', 'txt'})
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_extensions


def allowed_image(filename):
    """Check if a file is an allowed image type."""
    allowed_extensions = current_app.config.get('ALLOWED_IMAGE_EXTENSIONS', {'png', 'jpg', 'jpeg', 'gif', 'webp'})
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_extensions


def save_file(file, subfolder='submissions'):
    """Save an uploaded file and return the path."""
    if not file:
        return None
    
    filename = secure_filename(file.filename)
    # Add unique identifier to prevent collisions
    unique_filename = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}_{filename}"
    
    upload_folder = os.path.join(current_app.config['UPLOAD_FOLDER'], subfolder)
    os.makedirs(upload_folder, exist_ok=True)
    
    file_path = os.path.join(upload_folder, unique_filename)
    file.save(file_path)
    
    # Return relative path for database storage (use forward slashes for URL compatibility)
    return f"{subfolder}/{unique_filename}"


def save_image(file, subfolder='images'):
    """Save an uploaded image and return the path."""
    if not file or not allowed_image(file.filename):
        return None
    
    return save_file(file, subfolder)


def delete_file(file_path):
    """Delete a file from the upload folder."""
    if not file_path:
        return
    
    full_path = os.path.join(current_app.config['UPLOAD_FOLDER'], file_path)
    if os.path.exists(full_path):
        os.remove(full_path)


def slugify(text):
    """Convert text to URL-friendly slug."""
    text = text.lower().strip()
    text = re.sub(r'[^\w\s-]', '', text)
    text = re.sub(r'[-\s]+', '-', text)
    return text


def generate_unique_slug(text, model_class, existing_id=None):
    """Generate a unique slug for a model."""
    base_slug = slugify(text)
    slug = base_slug
    counter = 1
    
    while True:
        query = model_class.query.filter_by(slug=slug)
        if existing_id:
            query = query.filter(model_class.id != existing_id)
        
        if not query.first():
            break
        
        slug = f"{base_slug}-{counter}"
        counter += 1
    
    return slug


def get_file_extension(filename):
    """Get the extension of a file."""
    if '.' in filename:
        return filename.rsplit('.', 1)[1].lower()
    return ''


def format_date(date, format_str='%B %d, %Y'):
    """Format a datetime object to a string."""
    if date:
        return date.strftime(format_str)
    return ''


def truncate_text(text, length=200, suffix='...'):
    """Truncate text to a specified length."""
    if not text or len(text) <= length:
        return text
    return text[:length].rsplit(' ', 1)[0] + suffix


def strip_html_tags(text):
    """Remove HTML tags from text."""
    if not text:
        return ''
    clean = re.compile('<.*?>')
    return re.sub(clean, '', text)


def get_reading_time(text):
    """Estimate reading time for text (words per minute)."""
    if not text:
        return 1
    words = len(text.split())
    minutes = max(1, round(words / 200))
    return minutes
