# /// script
# requires-python = ">=3.11"
# dependencies = ["python-frontmatter"]
# ///
"""SessionStart-Hook: meldet Drift zwischen Vault-Skill-bundle_version
und der installierten Bundle-Version aus .docs/bundle.json.
Niemals Auto-Aktion.
"""
import json
import sys
from pathlib import Path

import frontmatter


def _vault_root(payload: dict) -> Path | None:
    cwd = payload.get("cwd")
    if not cwd:
        return None
    p = Path(cwd)
    return p if p.exists() else None


def _installed_bundle_version(vault: Path) -> str | None:
    f = vault / ".docs" / "bundle.json"
    if not f.exists():
        return None
    try:
        return json.loads(f.read_text(encoding="utf-8")).get("version")
    except (json.JSONDecodeError, OSError):
        return None


def _scan_drift(vault: Path, installed: str) -> list[dict]:
    skills = vault / ".claude" / "skills"
    if not skills.exists():
        return []
    drift = []
    for d in skills.iterdir():
        if not d.is_dir():
            continue
        sm = d / "SKILL.md"
        if not sm.exists():
            continue
        try:
            meta = dict(frontmatter.load(sm).metadata)
        except Exception:
            continue
        if "bundle_version" not in meta:
            continue
        bv = meta["bundle_version"]
        if bv is None:
            continue
        if str(bv) != installed:
            drift.append({"name": d.name, "vault": str(bv),
                          "installed": installed})
    return drift


def _parse_version(value: str) -> tuple[int, ...] | None:
    """Parst "X.Y.Z" zu (X, Y, Z); None, wenn kein numerisches Schema."""
    try:
        return tuple(int(p) for p in value.strip().split("."))
    except ValueError:
        return None


def _empfehlung(d: dict) -> str:
    """Gerichtete Empfehlung je Drift-Eintrag (v0.28.0).

    Vault älter als Bundle -> nachziehen (/skill-update); Vault neuer ->
    zurückspielen (/skill-to-bundle). Unparsebar oder gleichwertig ->
    richtungsblinder Fallback wie vor v0.28.0.
    """
    vv = _parse_version(d["vault"])
    iv = _parse_version(d["installed"])
    if vv is not None and iv is not None and vv < iv:
        return f"-> /skill-update {d['name']} (Vault-Skill älter als Bundle)"
    if vv is not None and iv is not None and vv > iv:
        return f"-> /skill-to-bundle {d['name']} (Vault-Skill neuer als Bundle)"
    return f"-> /skill-update {d['name']} oder /skill-to-bundle {d['name']}"


def main() -> int:
    try:
        payload = json.loads(sys.stdin.read() or "{}")
    except json.JSONDecodeError:
        return 0
    vault = _vault_root(payload)
    if not vault:
        return 0
    installed = _installed_bundle_version(vault)
    if installed is None:
        return 0
    drift = _scan_drift(vault, installed)
    if not drift:
        return 0
    sys.stderr.reconfigure(encoding="utf-8")
    print("bundle_version_drift_check:", file=sys.stderr)
    for d in drift:
        print(f"  - {d['name']}: Vault {d['vault']} <-> Bundle {d['installed']}"
              f" {_empfehlung(d)}",
              file=sys.stderr)
    return 0


if __name__ == "__main__":
    sys.exit(main())
