"""User-Bundle Loader.

Lädt zusätzlich zu den BUILTIN_BUNDLES alle TOML-Files aus
~/.local/share/taninux/bundles/<id>.toml.

Format:
    label = "My Setup"
    tagline = "alles was ich nach einer neuinstallation brauche"
    tags = ["personal"]
    packages = [
        "neovim",
        "git",
        "tmux",
    ]
"""
from __future__ import annotations

import tomllib
from pathlib import Path

from taninux.bundles.builtins import Bundle, BUILTIN_BUNDLES
from taninux.core.paths import bundles_dir


def load_user_bundles() -> list[Bundle]:
    bundles_path = bundles_dir()
    out: list[Bundle] = []
    for p in sorted(bundles_path.glob("*.toml")):
        try:
            data = tomllib.loads(p.read_text())
        except (OSError, tomllib.TOMLDecodeError):
            continue
        if "packages" not in data:
            continue
        out.append(Bundle(
            id=p.stem,
            label=data.get("label") or p.stem,
            tagline=data.get("tagline", ""),
            packages=tuple(data["packages"]),
            tags=tuple(data.get("tags", ())),
        ))
    return out


def all_bundles() -> list[Bundle]:
    return [*BUILTIN_BUNDLES, *load_user_bundles()]


def save_user_bundle(bundle_id: str, label: str, tagline: str,
                     packages: list[str], tags: list[str] | None = None) -> Path:
    """Schreibt ein User-Bundle als TOML."""
    safe_id = "".join(c if c.isalnum() or c in "-_" else "_" for c in bundle_id)
    target = bundles_dir() / f"{safe_id}.toml"

    lines = [
        f'label = "{label}"',
        f'tagline = "{tagline}"',
    ]
    if tags:
        tags_str = ", ".join(f'"{t}"' for t in tags)
        lines.append(f"tags = [{tags_str}]")
    lines.append("packages = [")
    for p in packages:
        lines.append(f'    "{p}",')
    lines.append("]")
    target.write_text("\n".join(lines) + "\n")
    return target
