import re
from functools import lru_cache
from pathlib import Path
from typing import Optional, Sequence

from pdcl_dss import Clip


class PDCLClipService:
    """Resolve clip_uuid to local clip cache path."""

    @staticmethod
    @lru_cache(maxsize=4096)
    def get_clip_path(clip_uuid: str) -> Optional[str]:
        clip = Clip(clip_uuid)
        files, _ = clip.list_files()
        if not files:
            return None
        return clip.get_cache_path(files[0])

    @staticmethod
    def _extract_timestamp_token(text: str) -> Optional[str]:
        if not text:
            return None

        patterns = (
            r"(20\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})",
            r"(20\d{2})[-_](\d{2})[-_](\d{2})[-_](\d{2})[-_](\d{2})[-_](\d{2})",
        )
        for pattern in patterns:
            match = re.search(pattern, text)
            if match:
                return "".join(match.groups())
        return None

    @staticmethod
    @lru_cache(maxsize=4096)
    def get_clip_sort_key(clip_uuid: str) -> tuple[int, str, str]:
        clip_path = PDCLClipService.get_clip_path(clip_uuid)
        candidates = []
        if clip_path:
            path = Path(clip_path)
            candidates.extend([path.name, str(path)])
        candidates.append(clip_uuid)

        for candidate in candidates:
            timestamp = PDCLClipService._extract_timestamp_token(candidate)
            if timestamp:
                return (0, timestamp, clip_uuid)
        return (1, clip_uuid, clip_uuid)

    @staticmethod
    def sort_clip_uuids(clip_uuids: Sequence[str]) -> list[str]:
        unique_clips = [
            clip_uuid
            for clip_uuid in dict.fromkeys(clip_uuids).keys()
            if clip_uuid
        ]
        return sorted(unique_clips, key=PDCLClipService.get_clip_sort_key)
