"""
fizko-mcp setup — installs MCP server + skills into Claude Code.

Usage:
    fizko-mcp-setup --api-key=KEY
    fizko-mcp-setup --api-key=KEY --company-id=UUID
    fizko-mcp-setup --uninstall
"""

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

SKILLS_DIR = Path(__file__).parent / "skills"


def _claude_settings_path() -> Path:
    """Get Claude Code settings.json path."""
    home = Path.home()
    return home / ".claude" / "settings.json"


def _load_settings() -> dict:
    path = _claude_settings_path()
    if path.exists():
        return json.loads(path.read_text())
    return {}


def _save_settings(settings: dict):
    path = _claude_settings_path()
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(settings, indent=2))


def install(api_key: str, api_url: str = "https://api.fizko.ai", company_id: str = ""):
    """Install fizko MCP server into Claude Code."""
    # 1. Add MCP server to Claude Code settings
    settings = _load_settings()
    mcp_servers = settings.setdefault("mcpServers", {})

    cmd = ["fizko-mcp"]
    if api_key:
        cmd.extend(["--api-key", api_key])
    if api_url != "https://api.fizko.ai":
        cmd.extend(["--api-url", api_url])
    if company_id:
        cmd.extend(["--company-id", company_id])

    mcp_servers["fizko"] = {
        "command": cmd[0],
        "args": cmd[1:],
    }

    _save_settings(settings)
    print(f"MCP server 'fizko' added to {_claude_settings_path()}")

    # 2. Copy skills to .claude/skills/
    skills_dest = Path.home() / ".claude" / "skills"
    skills_dest.mkdir(parents=True, exist_ok=True)

    copied = 0
    for skill_file in SKILLS_DIR.glob("*.md"):
        dest = skills_dest / skill_file.name
        shutil.copy2(skill_file, dest)
        copied += 1
        print(f"  Skill: {skill_file.name}")

    print(f"\n{copied} skills installed to {skills_dest}")
    print("\nDone! Restart Claude Code to use Fizko tools.")


def uninstall():
    """Remove fizko MCP server and skills from Claude Code."""
    # Remove MCP server
    settings = _load_settings()
    mcp_servers = settings.get("mcpServers", {})
    if "fizko" in mcp_servers:
        del mcp_servers["fizko"]
        _save_settings(settings)
        print(f"MCP server 'fizko' removed from {_claude_settings_path()}")
    else:
        print("MCP server 'fizko' not found in settings.")

    # Remove skills
    skills_dest = Path.home() / ".claude" / "skills"
    removed = 0
    for skill_file in SKILLS_DIR.glob("*.md"):
        dest = skills_dest / skill_file.name
        if dest.exists():
            dest.unlink()
            removed += 1

    print(f"{removed} skills removed.")


def main():
    parser = argparse.ArgumentParser(description="Install/uninstall Fizko MCP for Claude Code")
    parser.add_argument("--api-key", help="Fizko API key")
    parser.add_argument("--api-url", default="https://api.fizko.ai", help="Fizko API URL")
    parser.add_argument("--company-id", default="", help="Default company UUID")
    parser.add_argument("--uninstall", action="store_true", help="Remove Fizko from Claude Code")
    args = parser.parse_args()

    if args.uninstall:
        uninstall()
    elif args.api_key:
        install(args.api_key, args.api_url, args.company_id)
    else:
        parser.print_help()
        print("\nExample: fizko-mcp-setup --api-key=fizko_XXXXX")


if __name__ == "__main__":
    main()
