"""Shared installer logic."""

import json
import sys
import shutil
from pathlib import Path


def install(config_path: Path, restart_msg: str):
    client_id = input("Enter your PIERCLOUD_CLIENT_ID: ").strip()
    client_secret = input("Enter your PIERCLOUD_CLIENT_SECRET: ").strip()

    if not client_id or not client_secret:
        print("❌ Client ID and Secret are required!")
        sys.exit(1)

    mcp_path = shutil.which("piercloud-mcp")
    if not mcp_path:
        print("❌ piercloud-mcp not found in PATH!")
        sys.exit(1)

    config_path.parent.mkdir(parents=True, exist_ok=True)

    config = {}
    if config_path.exists():
        with open(config_path, "r") as f:
            config = json.load(f)

    if "mcpServers" not in config:
        config["mcpServers"] = {}

    config["mcpServers"]["piercloud"] = {
        "command": mcp_path,
        "env": {
            "PIERCLOUD_CLIENT_ID": client_id,
            "PIERCLOUD_CLIENT_SECRET": client_secret,
        },
    }

    with open(config_path, "w") as f:
        json.dump(config, f, indent=2)

    print(f"\n✅ Configuration saved to: {config_path}")
    print(f"✅ Command: {mcp_path}")
    print(f"\n🔄 {restart_msg}")
