"""Utilities that drive the modern Textual UI menus and presets."""

from __future__ import annotations

import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence

BASE_DIR = Path(__file__).resolve().parent
ROOT_DIR = BASE_DIR.parent
for path in (ROOT_DIR, BASE_DIR):
    str_path = str(path)
    if str_path not in sys.path:
        sys.path.insert(0, str_path)

import SYS.metadata as metadata


@dataclass(slots=True)
class PipelinePreset:
    """Simple descriptor for a reusable pipeline."""

    label: str
    description: str
    pipeline: str


PIPELINE_PRESETS: List[PipelinePreset] = [
    PipelinePreset(
        label="Download → Merge → Local",
        description=
        "Use download-file with playlist auto-selection, merge the pieces, tag, then import into local storage.",
        pipeline=
        'download-file "<url>" | merge-file | add-tags -store local | add-file -storage local',
    ),
    PipelinePreset(
        label="Download → Hydrus",
        description="Fetch media, auto-tag, and push directly into Hydrus.",
        pipeline=
        'download-file "<url>" | merge-file | add-tags -store hydrus | add-file -storage hydrus',
    ),
    PipelinePreset(
        label="Search Local Library",
        description=
        "Run search-file against the local library and emit a result table for further piping.",
        pipeline='search-file -library local -query "<keywords>"',
    ),
]


def load_tags(file_path: Path) -> List[str]:
    """Read tags for a file using metadata.py as the single source of truth."""

    try:
        return metadata.read_tags_from_file(file_path)
    except Exception:
        return []


def group_tags_by_namespace(tags: Sequence[str]) -> Dict[str, List[str]]:
    """Return tags grouped by namespace for quick UI summaries."""

    grouped: Dict[str,
                  List[str]] = {}
    for tag in metadata.normalize_tags(list(tags)):
        namespace, value = metadata.split_tag(tag)
        key = namespace or "_untagged"
        grouped.setdefault(key, []).append(value)

    for items in grouped.values():
        items.sort()
    return grouped


def normalize_tags(tags: Iterable[str]) -> List[str]:
    """Expose metadata.normalize_tags for callers that imported the old helper."""

    return metadata.normalize_tags(list(tags))
