"""Install this repository's skill; explicit updates preserve the complete old copy."""
from __future__ import annotations

import argparse
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import shutil
import sys
from uuid import uuid4

NAME = "cinematic-game-montage"
SOURCE = Path(__file__).resolve().parents[1] / "skills" / NAME


def install(skills_dir=None, update=False, source=SOURCE):
    source = Path(source).resolve(strict=True)
    if not (source / "SKILL.md").is_file():
        raise ValueError("source does not contain SKILL.md")
    home = Path(os.environ.get("CODEX_HOME") or (Path.home() / ".codex"))
    root = Path(skills_dir or (home / "skills")).expanduser().resolve()
    target = root / NAME
    if target.is_symlink() or root == source or source in root.parents or target == source or target in source.parents:
        raise ValueError("destination must be a separate, non-symlink skill directory")
    if target.exists() and not update:
        raise FileExistsError(f"{target} already exists; use --update to keep a backup and replace it")
    if target.exists() and not target.is_dir():
        raise ValueError("destination exists but is not a directory")
    root.mkdir(parents=True, exist_ok=True)
    stage = root / ("." + NAME + ".staging-" + uuid4().hex[:10])
    shutil.copytree(source, stage, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.pyo"))
    backup = None
    if target.exists():
        backups = (root.parent / "skill-backups").resolve()
        backups.mkdir(parents=True, exist_ok=True)
        stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
        backup = backups / f"{NAME}-{stamp}-{uuid4().hex[:8]}"
        # Both resolved roots are explicit; never move an arbitrary computed tree.
        if target.resolve().parent != root or backup.resolve().parent != backups:
            raise ValueError("unexpected update path")
        target.rename(backup)
    try:
        stage.rename(target)
    except OSError:
        if backup is not None and not target.exists():
            backup.rename(target)
        raise
    return {"installed": str(target), "backup": str(backup) if backup else None,
            "files": sum(p.is_file() for p in target.rglob("*"))}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--skills-dir", help="Override the personal skills directory")
    parser.add_argument("--update", action="store_true", help="Preserve the old skill in sibling skill-backups before replacing it")
    args = parser.parse_args()
    try:
        print(json.dumps(install(args.skills_dir, args.update), ensure_ascii=False, indent=2))
    except (OSError, ValueError) as exc:
        parser.exit(2, f"Error: {exc}\n")


if __name__ == "__main__":
    if hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(encoding="utf-8")
    main()
