import re
import os
import uuid
from pathlib import Path

def generate_slug(text: str) -> str:
    """Generate a URL-friendly slug from text"""
    # Convert to lowercase
    slug = text.lower()
    # Replace spaces and special characters with hyphens
    slug = re.sub(r'[^\w\s-]', '', slug)
    slug = re.sub(r'[\s_-]+', '-', slug)
    slug = re.sub(r'^-+|-+$', '', slug)
    return slug

def save_upload_file(upload_file, folder: str = "products", backend_url: str = None) -> str:
    """Save uploaded file and return the file URL"""
    # Create uploads directory if it doesn't exist
    upload_dir = Path("uploads") / folder
    upload_dir.mkdir(parents=True, exist_ok=True)
    
    # Generate unique filename
    file_extension = os.path.splitext(upload_file.filename)[1]
    unique_filename = f"{uuid.uuid4()}{file_extension}"
    file_path = upload_dir / unique_filename
    
    # Save file
    with open(file_path, "wb") as buffer:
        buffer.write(upload_file.file.read())
    
    # Return full URL if backend_url provided, otherwise relative path
    relative_path = f"/uploads/{folder}/{unique_filename}"
    if backend_url:
        # Remove trailing slash from backend_url if present
        backend_url = backend_url.rstrip('/')
        return f"{backend_url}{relative_path}"
    return relative_path
