"""FikoYT File Picker — ComfyUI input/output klasörlerini tarayıp dosya seç."""
import os

try:
    import folder_paths
except ImportError:
    folder_paths = None


_EXT_MAP = {
    "image": (".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif"),
    "audio": (".wav", ".mp3", ".flac", ".ogg", ".m4a", ".aac"),
    "video": (".mp4", ".mov", ".webm", ".mkv", ".avi"),
    "any":   tuple(),
}


def _base_roots():
    """input/output klasörlerini bul."""
    roots = []
    if folder_paths is not None:
        try:
            roots.append(("input", folder_paths.get_input_directory()))
            roots.append(("output", folder_paths.get_output_directory()))
        except Exception:
            pass
    if not roots:
        here = os.path.dirname(os.path.abspath(__file__))
        comfy_root = os.path.abspath(os.path.join(here, "..", "..", "..", ".."))
        roots = [
            ("input", os.path.join(comfy_root, "input")),
            ("output", os.path.join(comfy_root, "output")),
        ]
    return [(label, p) for label, p in roots if p and os.path.isdir(p)]


def _scan(file_type: str, folder_filter: str = ""):
    exts = _EXT_MAP.get(file_type, tuple())
    results = []
    for label, root in _base_roots():
        for dirpath, _dirs, files in os.walk(root):
            rel_dir = os.path.relpath(dirpath, root).replace("\\", "/")
            if rel_dir == ".":
                rel_dir = ""
            if folder_filter:
                # filtre "output/fikoyt" gibi → root etiketi + alt yol kontrol
                joined = f"{label}/{rel_dir}".rstrip("/")
                if folder_filter.lower() not in joined.lower():
                    continue
            for fn in files:
                if exts and not fn.lower().endswith(exts):
                    continue
                rel = f"{label}/{rel_dir}/{fn}".replace("//", "/")
                results.append(rel)
    results.sort()
    return results or ["(yok)"]


class FikoYTFilePicker:
    @classmethod
    def INPUT_TYPES(cls):
        # Varsayılan tarama: input + output, tüm görseller (ilk yükleme için makul liste).
        choices = _scan("image", "")
        return {
            "required": {
                "file_type": (["image", "audio", "video", "any"], {"default": "image"}),
                "folder_filter": ("STRING", {"default": ""}),
                "selection": (choices, {"default": choices[0]}),
                "label": ("STRING", {"default": "file"}),
            }
        }

    RETURN_TYPES = ("STRING",)
    RETURN_NAMES = ("path",)
    FUNCTION = "pick"
    CATEGORY = "FikoYT/util"

    def pick(self, file_type, folder_filter, selection, label):
        if not selection or selection == "(yok)":
            return ("",)
        # "input/foo/bar.png" gibi göreceli yolu mutlak yola çevir
        try:
            head, _, rest = selection.partition("/")
            roots = dict(_base_roots())
            base = roots.get(head)
            if base:
                full = os.path.join(base, rest.replace("/", os.sep))
                if os.path.isfile(full):
                    return (full,)
        except Exception:
            pass
        return (selection,)


NODE_CLASS_MAPPINGS = {"FikoYTFilePicker": FikoYTFilePicker}
NODE_DISPLAY_NAME_MAPPINGS = {"FikoYTFilePicker": "FikoYT • File Picker"}
