"""Установка Cluster SDK в окружение проекта. Используется только стандартная библиотека."""

from __future__ import annotations

import argparse
import json
import subprocess
import sys
import venv
from pathlib import Path

SDK_URL = "https://cluster.ninepeaks.dev/developers/downloads/cluster_sdk-0.1.1-py3-none-any.whl#sha256=fd12d441c44e3706bf30612771956801e6740dac3f64af525d24f120d1d1eb08"


def setup(path: Path, *, name: str | None = None, environment: str = ".venv", existing: bool = False) -> None:
    if sys.version_info < (3, 12): raise RuntimeError("Python 3.12 or newer is required")
    path = path.resolve()
    path.mkdir(parents=True, exist_ok=True)
    target = path / environment
    python = target / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")
    if not python.is_file(): venv.EnvBuilder(with_pip=True).create(target)
    if subprocess.run([str(python), "-m", "pip", "--version"], capture_output=True).returncode:
        subprocess.run([str(python), "-m", "ensurepip", "--upgrade"], check=True)
    # Старый stub-only пакет имеет приоритет у Pylance и скрывал бы новый SDK.
    previous = subprocess.run([str(python), "-m", "pip", "show", "cluster-sdk-types"], capture_output=True)
    if previous.returncode == 0:
        subprocess.run([str(python), "-m", "pip", "uninstall", "-y", "cluster-sdk-types"], check=True)
    subprocess.run([str(python), "-m", "pip", "install", "--upgrade", "cluster-sdk[dev] @ " + SDK_URL], check=True)
    argv = [str(python), "-m", "cluster_sdk", "init", str(path)]
    if name: argv.extend(["--name", name])
    if existing: argv.append("--existing")
    subprocess.run(argv, check=True)
    print(json.dumps({"project": str(path), "python": str(python), "sdk": "installed"}))


def main() -> int:
    parser = argparse.ArgumentParser(description="Install Cluster SDK into a project environment")
    parser.add_argument("path", nargs="?", type=Path, default=Path.cwd())
    parser.add_argument("--name")
    parser.add_argument("--venv", default=".venv", help="Project environment directory")
    parser.add_argument("--existing", action="store_true", help="Configure SDK without creating a module template")
    args = parser.parse_args()
    try: setup(args.path, name=args.name, environment=args.venv, existing=args.existing)
    except (OSError, RuntimeError, subprocess.CalledProcessError) as error:
        print(f"SDK setup failed: {error}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__": raise SystemExit(main())
