"""Dataset selector files: plain-text views over the shared catalog."""

from __future__ import annotations

from datetime import datetime, timezone
from pathlib import Path

from rich.console import Console

from xc_dl.core.manifest import ManifestEntry
from xc_dl.utils import sanitise_path_component

console = Console()


def selector_filename(name: str, version: int) -> str:
    """Return the filename for a selector: dataset_manifest_{name}_v{version}.txt"""
    return f"dataset_manifest_{name}_v{version}.txt"


def next_version(data_dir: Path, name: str) -> int:
    """Find the next version number by globbing existing selector files."""
    pattern = f"dataset_manifest_{name}_v*.txt"
    existing = list(data_dir.glob(pattern))
    if not existing:
        return 1
    max_ver = 0
    for p in existing:
        stem = p.stem  # dataset_manifest_{name}_v{N}
        try:
            ver = int(stem.rsplit("_v", 1)[-1])
            max_ver = max(max_ver, ver)
        except (ValueError, IndexError):
            pass
    return max_ver + 1


def derive_selector_name(query: str, preset_name: str | None = None) -> str:
    """Derive a selector name from a preset name or sanitized query."""
    if preset_name:
        return sanitise_path_component(preset_name)
    sanitized = sanitise_path_component(query.lower().replace(" ", "-"))
    return sanitized[:80]


def write_selector(
    data_dir: Path,
    name: str,
    query: str,
    entries: list[ManifestEntry],
    version: int | None = None,
) -> Path | None:
    """Write a selector file listing metadata paths for the given entries.

    Returns the path to the written file, or None if entries is empty.
    """
    if not entries:
        console.print("[dim]No entries — selector file not written.[/]")
        return None

    if version is None:
        version = next_version(data_dir, name)

    paths = sorted(e.metadata_path for e in entries)
    fname = selector_filename(name, version)
    out = data_dir / fname

    now = datetime.now(timezone.utc).isoformat()
    lines = [
        "# xc-dl dataset selector",
        f"# name: {name}",
        f"# query: {query}",
        f"# version: {version}",
        f"# created: {now}",
        f"# count: {len(paths)}",
    ]
    lines.append("")
    lines.extend(paths)
    lines.append("")

    out.write_text("\n".join(lines))
    return out


def read_selector(path: Path) -> tuple[dict[str, str], list[str]]:
    """Parse a selector file into header dict and list of metadata paths."""
    header: dict[str, str] = {}
    paths: list[str] = []
    for line in path.read_text().splitlines():
        line = line.strip()
        if line.startswith("#"):
            # Parse "# key: value"
            content = line.lstrip("#").strip()
            if ": " in content:
                key, val = content.split(": ", 1)
                header[key] = val
        elif line:
            paths.append(line)
    return header, paths
