"""Shared naming and listing contract for domestic-offer media files."""
from __future__ import annotations

import os
import re

from modules.core import storage_paths


OFFER_IMAGE_EXTENSIONS = (".jpg", ".jpeg", ".png", ".webp")
EDITABLE_IMAGE_EXTENSIONS = (".jpg", ".jpeg", ".png")
OFFER_IMAGE_RE = re.compile(
    r"^image_(?P<id>\d+)_url_\d+\.(jpg|jpeg|png|webp)$", re.IGNORECASE
)


def offer_directory(offer_id):
    return storage_paths.offer_dir(offer_id)


def image_prefix(offer_id):
    return f"image_{offer_id}_url_"


def image_filename(offer_id, index, extension):
    return f"{image_prefix(offer_id)}{index}{extension}"


def description_filename(offer_id):
    return f"description_{offer_id}.md"


def description_path(offer_id):
    return offer_directory(offer_id) / description_filename(offer_id)


def read_description_text(offer_id):
    path = description_path(offer_id)
    if not os.path.isfile(path):
        return ""
    try:
        with open(path, "r", encoding="utf-8") as handle:
            return handle.read().strip()
    except Exception:
        return ""


def image_index(filename, fallback=10**9):
    try:
        return int(str(filename).split("_url_")[-1].split(".")[0])
    except Exception:
        return fallback


def list_image_filenames(
    offer_id,
    *,
    extensions=OFFER_IMAGE_EXTENSIONS,
    numeric_sort=False,
    case_sensitive_prefix=False,
):
    """List matching files while preserving each caller's historical ordering.

    CRM's list endpoint exposes filesystem order, whereas cards and Website use
    numeric image order.  The flags make that existing distinction explicit.
    """
    directory = offer_directory(offer_id)
    if not os.path.isdir(directory):
        return []

    prefix = image_prefix(offer_id)
    allowed = tuple(extension.lower() for extension in extensions)
    files = []
    for name in os.listdir(directory):
        candidate = name if case_sensitive_prefix else name.lower()
        expected = prefix if case_sensitive_prefix else prefix.lower()
        if not candidate.startswith(expected):
            continue
        if os.path.splitext(name.lower())[1] not in allowed:
            continue
        files.append(name)

    if numeric_sort:
        files.sort(key=lambda name: (image_index(name), name.lower()))
    return files
