import os
import random
from django.utils import timezone


def transport_vehicle_upload_path(instance, filename):
    """
    Generate upload path for transport vehicle documents:
    transport/vehicles/{vehicle_id}/{filename}
    """
    ext = filename.split(".")[-1] if "." in filename else ""
    timestamp = timezone.now().strftime("%Y%m%d_%H%M%S")

    # Get vehicle ID (for new objects that don't have ID yet)
    vehicle_id = getattr(instance, "id", None)

    # If no ID exists (new object), use a temporary identifier
    if vehicle_id is None:
        # Generate a temporary ID based on vehicle number or timestamp
        vehicle_number = getattr(instance, "vehicle_number", "new")
        vehicle_id = f"{vehicle_number}_{timestamp}"

    # Create filename with timestamp
    new_filename = (
        f"vehicle_doc_{vehicle_id}_{timestamp}.{ext}"
        if ext
        else f"vehicle_doc_{vehicle_id}_{timestamp}"
    )

    # Return the complete path
    return f"transport/vehicles/{vehicle_id}/{new_filename}"


def transport_vehicle_insurance_upload_path(instance, filename):
    """
    Generate upload path for vehicle insurance documents:
    transport/vehicles/{vehicle_id}/insurance/{filename}
    """
    ext = filename.split(".")[-1] if "." in filename else ""
    timestamp = timezone.now().strftime("%Y%m%d_%H%M%S")

    vehicle_id = getattr(instance, "id", None)

    if vehicle_id is None:
        vehicle_number = getattr(instance, "vehicle_number", "new")
        vehicle_id = f"{vehicle_number}_{timestamp}"

    new_filename = (
        f"insurance_{vehicle_id}_{timestamp}.{ext}"
        if ext
        else f"insurance_{vehicle_id}_{timestamp}"
    )

    return f"transport/vehicles/{vehicle_id}/insurance/{new_filename}"


def transport_vehicle_permit_upload_path(instance, filename):
    """
    Generate upload path for vehicle permit documents:
    transport/vehicles/{vehicle_id}/permit/{filename}
    """
    ext = filename.split(".")[-1] if "." in filename else ""
    timestamp = timezone.now().strftime("%Y%m%d_%H%M%S")

    vehicle_id = getattr(instance, "id", None)

    if vehicle_id is None:
        vehicle_number = getattr(instance, "vehicle_number", "new")
        vehicle_id = f"{vehicle_number}_{timestamp}"

    new_filename = (
        f"permit_{vehicle_id}_{timestamp}.{ext}"
        if ext
        else f"permit_{vehicle_id}_{timestamp}"
    )

    return f"transport/vehicles/{vehicle_id}/permit/{new_filename}"
